在 C++ 中,常量成员函数(const member function) 是指通过 const 关键字修饰的成员函数,表示该函数不会修改类的成员变量(除了标记为 mutable 的成员)。这种机制增强了代码的安全性和可读性,明确表达了函数的意图。
class Student {
public:
mutable int age;
string name;
Student(string name, int age)
{
this->name = name;
this->age = age;
}
void Say() const
{
this->age = 35;
cout << "My name is " + name << endl;
}
};
int main()
{
Student st = Student("HX",33);
st.Say();
}
在方法后面加入const的就是常量成员函数。
在常量成员函数中,this 指针的类型是 const ClassName*,即指向常量的指针
只有常量成员函数才能被 const 对象调用
279

被折叠的 条评论
为什么被折叠?



