C++类中的const和mutable

当类中的方法之后加上const代表这个方法中的类中的变量不可以被修改,如果需要修改类中的变量,需要在变量前加上mutable ;那么这个变量在类的const方法中可以被修改。

class A {
public:
    int a;

void test() const {
   a = 10; // 错误,因为const方法中的类中的变量不可被修改。
}
};

就像这样:

class A {
public:
    mutable int a;

void test() const {
   a = 10; // 正确,因为const方法中的类中的mutable变量可被修改。
}
};

猜你喜欢

转载自blog.csdn.net/m0_37844072/article/details/120928867