为什么即使在const函数中值也会改变?

ell*_*lle 5 c++

#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();
}
Run Code Online (Sandbox Code Playgroud)

GMa*_*ckG 14

因为你要扔掉const......

当你施展某些东西时,你的责任就是确保它不会做一些愚蠢的事情.


请注意,如果temp t;更改为const temp t;,则会出现未定义的行为,用于修改const值.

巧合的是,我只是在我的博客中提到了这一点.(几乎相同的功能.)


Chu*_*dad 5

$ 5.4/5是关于explicit type conversion(这是在这里使用的)

由...执行的转换

- const_cast(5.2.11),

- static_cast(5.2.9),

- static_cast后跟const_cast,

- reinterpret_cast(5.2.10),或

- 一个reinterpret_cast,然后是一个const_cast,

可以使用显式类型转换的强制转换表示法执行.适用相同的语义限制和行为.如果转换可以用上面列出的多种方式解释,则使用列表中首先出现的解释,即使由该解释产生的转换是格式错误的. 如果转换可以多种方式解释为static_cast后跟const_cast,则转换形式不正确.

在这种情况下,((temp*)this)得到了对待(const_cast<temp *>(this))和良好的形式.这删除了constness,从而允许更改类成员值.