如何获取对象的const引用并使用该引用更改对象(使用const_cast)
How to get a const reference to an object and change the object using that reference (Using const_cast)?
我有一个成员函数,返回一个类实例的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引用
相关文章:
- 在 const 函数中通过引用和指针返回之间的区别
- 使用对const结构的const数组的引用进行构造
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 在C++17中,引用const字符串的语义应该是什么
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 类型为 "Bucket&"(未限定的 const 限定)的引用不能使用 "SortedList." 类型的值进行初始化 如何修复此错误?
- 为什么在引用指针时将 const 放在 & 符号的左侧有效,而在右侧则无效?
- 将返回类型专用化为 void 或 const 左值引用
- 在其他容器中使用 boost::container::static_vector 时,GCC 编译错误"将'const s'绑定到类型's&'的引用丢弃限定符"
- 在 C++ 中通过引用传递类成员时,Const 不起作用
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 错误:对类型 'const ItemInstance' 的引用无法绑定到类型 'void' 的右值
- 包括"lvtocon.h",未定义对'operator<<(std::ostream&, char const*)的引用
- 如何在构造函数中传递 const 引用时强制编译器不接受右值
- 通过使用 const-cast 的非常量引用来延长临时的寿命
- const TYPE&- 我什么时候想通过引用 const 来使用?
- 指针引用const null值
- 三元运算符和通过引用const延长临时对象的生存期
- 为什么必须引用const来避免复制形参?