是否可以在"const"函数中更改Member变量的值?

9 c++ visual-c++

常量变量的值可以通过指针技巧来改变,但是可以做这样的事情:

    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)
  • 答:声明某些成员可变.
  • B:const_cast从this指针中删除constness .


Ade*_*mad 7

虽然这不被赞赏,但 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_cast`,这是一个不完整的答案。 (2认同)

eml*_*lai 6

了解这里最重要的是按位/物理/混凝土const内斯和概念/ meaningwise /逻辑/抽象const内斯。

简而言之:

  • 如果函数是概念上的 const,则制作成员数据mutable。
  • 否则,使函数非const。