C++ 类class const修饰成员函数

tech2022-10-14  100

常函数:

成员函数后加const后我们称这个函数为常函数常函数内不可以修改成员属性成员属性声明关键字mutable后,在常函数中依然可以修改

常对象:

声明对象加const称该对象为常对象常对象只能调用常函数 #include <iostream> using namespace std; class Person { public: int m_a; mutable int m_b; void showPerson() const //常函数不可以修改成员属性 { //this->m_a=10; //成员函数后面加const 修饰的是this指向,让指针指向的值也不可以修改 this->m_b=10; cout<<m_b<<endl; } void showNull(){} //普通成员函数 Person(){} }; //1.常函数 void func1() { Person p; p.showPerson(); } //2.常对象 void func2() { const Person p; //常对象 // p.m_a=100; //不可修改常对象的成员 p.m_b=100; //mutable关键字作用 常对象下也可修改 p.showPerson(); // p.showNull(); //常对象只能调用常函数 } int main() { func1(); func2(); return 0; }
最新回复(0)