1

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

例子:

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

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

此外,通过执行以下操作,我能够在不使用 const_cast 的情况下实现我想要的:(假设已经有一个 State 实例调用state1

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 引用甚至调用 setter 的函数中获取非常量引用?

感谢您的关注

4

2 回答 2

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

它有效,因为那不是参考。您正在制作 const 值的副本。尝试这个:

City & ref = state1.getReference();

那是行不通的。您可以像这样使用 const cast:

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

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

于 2011-12-13T03:07:05.793 回答
0

如果你声明了某个东西const,就像你向编译器做出承诺一样,你永远不会改变那个东西中的内容,你为什么要这么做?

如果您真的想更改 const 类型中的某些内容,则必须声明mutable

class A
{
public:
mutable int _change_me;
};

现在您可以更改成员_change_me,即使您有class A.

于 2011-12-13T02:59:15.610 回答