请参阅此页面并转到示例.这是关于使用的演示
struct type {
type() :i(3) {}
void m1(int v) const {
// this->i = v; // compile error: this is a pointer to const
const_cast<type*>(this)->i = v; // OK as long as the type object isn't const
}
int i;
};
Run Code Online (Sandbox Code Playgroud)
const这里意味着m1无法修改类型的成员变量.我不明白为什么const_cast会修改常量性这个.我的意思是,这个指针指向当前类型对象,而不是i本身.
为什么不:
const_cast<int>((this)->i) = v;
Run Code Online (Sandbox Code Playgroud)
我可以说当一个成员函数使用const限定符时,整个对象和所有成员变量都变为const吗?为什么这是const指针?
我无法理解为什么const_cast会修改它的常量
它没有.你可以说它创建了另一个临时指针,它不是指向a的指针const type,但包含与之相同的地址this.然后它使用该指针进行访问i.
为什么不
const_cast<int>((this)->i)
你可以这样做,但你需要一个转换为引用,而不是一个普通的整数.
const_cast<int&>(i) = v; // this-> omitted for brevity
Run Code Online (Sandbox Code Playgroud)
同样的警告适用于对一个真正为 const 的对象的iif this点的任何修改.
我可以说当一个成员函数使用一个const修饰符时,整个对象和所有成员变量都成为const吗?为什么这是const指针?
是.成员函数上的const限定符意味着this指针类型是type const.并且所有成员(不可变)也是const的任何访问权限this.