为什么不能将const X转换为X&?

Tan*_*uiz 14 c++ const reference

我试图在俄罗斯方块项目上理解并实现const正确性.

这是一个经常出现的问题,当我试图添加const时,我认为这是必要的.

我有一个(Piece)类,其中一个类的私有成员是

Point rotationCenter;
Run Code Online (Sandbox Code Playgroud)

而我正在尝试写一个这样的吸气剂:

inline Point & Piece::getRotationCenter() const
{
  return rotationCenter;
}
Run Code Online (Sandbox Code Playgroud)

以前,我有相同的吸气剂,但不是作为const功能,并且正在工作.现在,我得到了C2240错误"无法将const Point转换为Point&".

我该怎么做才能纠正这个问题?我应该离开getRotationCenter没有const

PS:我阅读https://isocpp.org/wiki/faq/const-correctness作为教程.

son*_*yao 33

为什么不能转换const XX &

因为如果允许,以下危险代码变为有效:

const int x = 0;
int& rx = x;     // bind const variable to reference (to non-const)
rx = 99;         // oops, try to modify the const variable via the reference
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能纠正这个问题?我应该离开getRotationCenter没有const

这取决于你的意图.如果可以修改返回的对象,则使成员函数非const并返回Point&.如果没有,则保留成员函数const并生成返回类型const Point&.const成员函数是指不会修改(或提供修改)对象(及其成员)的承诺.

  • const成员函数意味着它不会修改对象的承诺,*也不会打开被修改对象的大门*.返回一个'Point &`不会修改`Point`,它只是"打开门". (12认同)

Tar*_*ama 13

内部const成员函数是数据成员的所有类const.您不能将非const引用绑定到您的const成员数据,因此您会收到编译器错误.

如果您不希望调用者进行修改rotationCenter,则可以通过Point或返回const Point&.

inline const Point & Piece::getRotationCenter() const
{
  return rotationCenter;
}
Run Code Online (Sandbox Code Playgroud)

如果你确实希望调用者修改rotationCenter(我通常不推荐),写两个重载:一个返回Point&,一个返回const Point&依赖于你调用它的对象的限定:

inline Point & Piece::getRotationCenter() //not const
{
  return rotationCenter;
}

inline const Point & Piece::getRotationCenter() const
{
  return rotationCenter;
}
Run Code Online (Sandbox Code Playgroud)