我们前面学过const修饰的常指针,
在常指针定义的时候需要初始化,且后续不可以再改变。
那么今天我们学习一下常成员函数和常对象。
常成员函数: 格式如下
void memFunc(void) const
常对象:
const Person *p = new Person();
语法很简单,但是我们在使用的时候要注意:
常成员函数只能被调用,不能修改成员变量,除非成员变量有mutable关键字修饰。
而常对象只能调用常成员函数,因为常对象不能修改成员变量。
除非成员变量用mutable关键字修饰。
下面我们举例说明:
/****************************************************
* brief : const修饰成员函数和对象
* author : shao
* date : 2020-03-06
* note : none
*
****************************************************/
#include <iostream>
using namespace std;
class Person{
public:
Person()
{
this->p_age = 0;
this->p_ID = 0;
}
/* const 修饰后不能修改
* 成员变量数据,除非该成员变量有mutable修饰
*/
void operateData(void) const
{
//this->p_age = 10; //这行编译不能过,const成员不可修改成员变量
this->p_ID = 20; //这行编译可以过,p_ID是mutable修饰的
//this->getNum = 30; //静态变量也不可以修改
cout << "p_age = " << this->p_age << endl;
cout << "p_ID = " << this->p_ID << endl;
//cout << "getNum = " << getNum << endl;
}
int p_age;
mutable int p_ID;
static int getNum;
};
void test01(void)
{
Person *p = new Person();
p->operateData();
}
/*
* 常对象只能调用常成员函数,
* 如果想要修改成员变量,那么必须要是mutable修饰
*
*
*/
class NewPerson{
public:
NewPerson()
{
this->p_age = 0;
this->p_ID = 0;
}
//常成员函数
void setNewPerson(void) const
{
//this->p_age = 15; //本行编译不过,常成员函数不能修改成员变量
this->p_ID = 25; //本行成员变量有mutable修饰,可以编译通过
}
void showInfo(void)
{
this->p_age = 35;
cout << "NewPerson age: " << this->p_age << endl;
cout << "NewPerson ID :" << this->p_ID << endl;
}
int p_age;
mutable int p_ID;
};
void test02(void)
{
const NewPerson *np = new NewPerson();
np->setNewPerson(); //常成员函数可以调用
// np->showInfo();//不可以调用,因为普通成员函数可能会修改成员变量的值
np->p_ID = 36; //可以修改mutable 变量
//np->showInfo(); //这是常对象调用普通成员函数,不可以
}
int main(void)
{
test01();
cout <<"========================华丽的分割线==================\n" << endl;
test02();
return 0;
}
运行结果如下:
test02中的常对象没法调用普通成员函数,因为普通成员函数有可能会修改变量。
这与const的初衷相违背,故只能有test01的内容被打印出来。