我有一个成员函数返回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 的函数中获取非常量引用?
感谢您的关注