构造析构函数不能加限定符
在实际开发中如果成员函数不会修改成员变量,就应该加上const,这是C++的编程规范,就像const修饰函数形参一样。后人看见成员函数有const修饰就不会修改成员变量
#include<iostream>
using namespace std;
class person {
public:
string name;
mutable int age;
person(const string& name,const int& age) :name(name), age(age) {};
void f(){};
void show() const
{ cout << name << " " << ++age; //mutable可以突破const的限制 }
void operator()() const
{
cout<<"operator_const"<<endl;
}
void operator()()
{
cout<<"operator"<<endl;
}
};
int main()
{
person p("西施", 19);
p.show();
p(); //仿函数
person p2("貂蝉",18);
p2() //仿函数
return 0;
}
mutable可以突破const的限制,被mutable修饰的成员变量,永远处于可变状态
1非const成员函数可以调用const和非const成员函数;const成员函数只能调用const成员函数
2非const对象可以调用const和非const成员函数;const对象只能调用const成员函数,在仿函数中同样适用
person p("西施", 19);
p.show();
p.f();
const person p2("貂蝉", 18);
p2.show();
//p2.f(); //err