#include<iostream>
using namespace std;
class temp
{
int value1;
public :
void fun() const
{
((temp*)this)->value1 = 10;
}
void print()
{
cout<<value1<<endl;
}
};
int main()
{
temp t;
t.fun();
t.print();
}
最佳答案
因为你要丢弃 const
...
当你转换某些东西时,你有责任确保它不会做一些愚蠢的事情。
请注意,如果 temp t;
更改为 const temp t;
,您将获得未定义的行为,用于修改 const
值。
巧合的是,我刚刚在 my blog 中提到了这一点. (也几乎相同的功能。)
关于c++ - 为什么即使在 const 函数中也会更改值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3574059/