1.const成员函数
const成员函不能修改对象的状态,只能访问对象的值
#include <iostream>
using namespace std;
class A
{
private:
int x_;
mutable int count_; //可以在const函数中进行修改操作
public:
A(int x):x_(x),count_(0)
{
}
void display()
{
cout<<x_<<endl;
}
void display() const //const成员函数,两个函数可以构成重载
{ //这里面的语句不能有对成员值的修改操作
cout<<"const成员函数"<<x_<<endl;
//x_++; //error
count_++;
}
void showCount() const
{
cout<<count_<<endl;
}
};
int main()
{
A a(10);
a.display(); //调用普通的display函数,也可以调用const成员函数
const A a1(20);
a1.display(); //调用const display函数,不能调用非const成员函数
a1.display();
a1.showCount(); //2
return 0;
}
2.const成员函数可以修改
mutable类型的值
#include <iostream>
using namespace std;
class A
{
private:
int x_;
mutable int count_; //可以在const函数中进行修改操作
public:
A(int x):x_(x),count_(0)
{
}
void display()
{
cout<<x_<<endl;
}
void display() const //const成员函数,两个函数可以构成重载
{ //这里面的语句不能有对成员值的修改操作
cout<<"const成员函数"<<x_<<endl;
//x_++; //error
count_++;
}
void showCount() const
{
cout<<count_<<endl;
}
};
int main()
{
A a(10);
a.display(); //调用普通的display函数
const A a1(20);
a1.display(); //调用const display函数,不能调用非const成员函数
a1.display();
a1.showCount(); //2
return 0;
}