在前边几章的内容中,我们知道C++的类中可以有const成员变量,并且还知道类中的const成员变量只能在初始化列表中初始化。同样,在C++中,还存在const对象以及const成员函数,const修饰的对象为只读对象,他们的特性如下:
const成员函数的定义:需要在函数的声明及定义的后边加上const关键字
-const对象只能调用const成员函数
-const成员函数只能调用const成员函数
-const成员函数中不能改变成员变量的值
下边以一段代码来验证一下:
#include <iostream>
#include <string>
using namespace std;
class test
{
private:
int m_value;
public:
void fun1(int value) const
{
m_value = value; //error, 不能在const成员函数中改变成员变量的值
fun2(); //OK, const成员函数只能调用const成员函数
fun3(); //error, const成员函数不能调用非const成员函数
}
void fun2() const
{
fun1(34);
}
void fun3()
{
fun1(34); //OK, 非const 成员函数中可以调用const成员函数
}
};
int main()
{
const test t; //定义一个const对象
t.fun1(