如何获取对象的const引用并使用该引用更改对象(使用const_cast)

How to get a const reference to an object and change the object using that reference (Using const_cast)?

本文关键字:引用 const 对象 使用 cast 取对象 何获      更新时间:2023-10-16

我有一个成员函数,返回一个类实例的const引用。

的例子:

class State
{
  const City* city1;
public:
  State(const City& c) : city1(c) {}
  const City& getReference() const {return *city1;}
  void changeStuff();
};

如何使用const_cast和getReference()获得指向city1的非const City * ?

同样,通过以下操作,我可以在不使用const_cast的情况下实现我想要的:(假设已经有一个名为state1的State实例)

City ref = state1.getReference(); //Why does it work?
City * ptr = &ref; //This is what I wanted, but not this way
ref->changeStuff(); //How can I call functions changing things if the reference was constant?

我如何能够从返回const引用的函数中获得非const引用,甚至调用setter ?

谢谢你的关注

City ref = state1.getReference(); //Why does it work?

之所以有效是因为它不是引用。你在复制const值。试试这个:

City & ref = state1.getReference();

那不行。你可以像这样使用const强制转换:

City * ptr = const_cast<City*>(&state1.getReference());

只要确保对象不是真正的const即可。否则尝试修改它就是未定义行为

如果你已经声明了一些东西是const,就像你对编译器承诺的那样,你永远不会改变那个东西的内容,你为什么要这样做呢?

如果你真的想改变const类型,你必须声明mutable:

class A
{
public:
mutable int _change_me;
};

现在你可以改变成员_change_me,即使你有class A的const引用

相关文章: