常量变量的值可以通过指针技巧来改变,但是可以做这样的事情:
class A (){
int x;
public:
void func () const {
//change value of x here
}
}
Run Code Online (Sandbox Code Playgroud)
joh*_*hao 28
宣布 x mutable
class A (){
mutable int x;
public:
void func () const {
//change value of x here
}
};
Run Code Online (Sandbox Code Playgroud)
bku*_*ytt 11
您有两种选择:
class C
{
public:
void const_f() const
{
x = 5; // A
auto* p_this = const_cast<C*>(this); // B
p_this->y = 5;
}
private:
mutable int x; // A
int y;
};
Run Code Online (Sandbox Code Playgroud)
this指针中删除constness .虽然这不被赞赏,但 C++ 提供了“后门”,可以用来违反自己的规定,就像脏指针技巧一样。无论如何,您可以使用“This”指针的强制转换版本轻松完成此操作:
class A (){
int x;
public:
void func () const {
//change value of x here
A* ptr = const_cast<A*> (this);
ptr->x= 10; //Voila ! Here you go buddy
}
}
Run Code Online (Sandbox Code Playgroud)
了解这里最重要的是按位/物理/混凝土const内斯和概念/ meaningwise /逻辑/抽象const内斯。
简而言之:
const,则制作成员数据mutable。const。| 归档时间: |
|
| 查看次数: |
10518 次 |
| 最近记录: |