#include <iostream>
#include <string>
class Person {
public:
Person(const std::string& name) : name_(name), age_(0) {}
void introduce() const {
// 即使在常量方法中,也可以修改 mutable 成员变量
++count_;
std::cout << "My name is " << name_ << ", and I am " << age_ << " years old." << std::endl;
std::cout << "This introduction has been given " << count_ << " times." << std::endl;
}
void setAge(int age) {
age_ = age;
}
private:
std::string name_;
int age_;
mutable int count_ = 0; // mutable 成员变量可以在常量方法中被修改
};
int main() {
Person person("Alice");
person.setAge(30);
person.introduce(); // 输出: My name is Alice, and I am 30 years old. This introduction has been given 1 times.
person.introduce(); // 输出: My name is Alice, and I am 30 years old. This introduction has been given 2 times.
return 0;
}
在这个示例代码中,我们定义了一个 Person
类,其中包含一个 mutable
成员变量 count_
。这个成员变量的作用是记录 introduce
方法被调用的次数。
mutable
关键字允许在常量成员函数(即带有 const
修饰符的方法)中修改该成员变量。introduce
方法中,尽管它是常量方法,但我们仍然可以增加 count_
的值,因为它是 mutable
的。通过这个例子,可以看到 mutable
的作用是提供一种机制,使得某些特定的成员变量可以在常量方法中被修改,而不会破坏对象的逻辑不变性。
上一篇:c++数字转字符串
下一篇:c++ 11
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站