c++ - 为什么即使在 const 函数中也会更改值?

标签 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();
}

最佳答案

因为你要丢弃 const...

当你转换某些东西时,你有责任确保它不会做一些愚蠢的事情。


请注意,如果 temp t; 更改为 const temp t;,您将获得未定义的行为,用于修改 const 值。

巧合的是,我刚刚在 my blog 中提到了这一点. (也几乎相同的功能。)

关于c++ - 为什么即使在 const 函数中也会更改值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3574059/

相关文章:

C++ 初学者 : what is the point of using a variable by reference if using "const"?

c++ - 如何从具有特定 HWND 的窗口中获取文本?

c++ - 有没有办法在 Emacs 中同时启用 Objective-C 模式和 C++ 模式?

c++ - 基于范围的 for 循环等价物

c++ - istream (ostream) 与 bool

C++ boost 正则表达式替换为条件

c++ - QODBCResult::exec:无法执行语句:“[Microsoft][ODBC SQL Server Driver]COUNT 字段不正确或语法错误

c++ - C++中字符串和char数组声明的时间复杂度有什么区别?

c++ - 使用自定义元数据嵌入视频流

c++ - 有人试过在 Windows 上编译 Go 吗?它现在似乎支持生成 PE 格式的二进制文件