如果我们将变量声明为 const,即使通过非 const 引用,其内容也不得更改。在下面的代码中,我不明白为什么我会根据类型(原始与对象)得到不同的行为:
#include <iostream>
class MyClass
{
public:
int m_value ;
MyClass(int value): m_value(value) {} ;
}
int main()
{
const int x = 0 ;
const_cast<int &>(x)=20 ;
std::cout << x << std::endl ; //output 0
const MyClass a(0) ;
const_cast<MyClass&>(a).m_value= 20 ;
std::cout << a.m_value << std::endl ; //output 20
}
最佳答案
你不能抛弃常量变量 x 的常量性,因为变量 x 是一个常量变量。
const_cast
实际上做的是抛弃 const 指针或引用,因为您的成员 m_value
不是 const 成员,您可以使用 const_cast
int x = 0 ;
const int& p = x;
// p = 20; // error: p is const
const_cast<int &>(p)=20 ;
std::cout << p << std::endl ; //output 20
-------------------------------------------
我的类(class)
{
公开:
const int m_value = 0;
};
int main(){
const MyClass a;
const_cast<MyClass&>(a).m_value= 20 ;// undefined behavior
}
关于c++ - const_cast 不同的行为 : primitive type vs object type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54569144/