1.常函数
1.定义
成员函数后面加const
class person
{
public:
void show()const
{
age = 100;
}
int age;
};
报错信息
原因:age=this->age
this指针的本质是指针常量 (const在指针变量前面,表示指向不可以改)
也就是this= person * const this;
而在其前面加了个cosnt变成了:const int * const this;
所以指向不可以改,指向的值也不可以改
成员函数后面加const的本质:
修饰的是this指向,让指针指向的值也不可以修改。
2.作用
常函数内不可以修改成员属性
3.注意
成员属性在声明时加关键字mutable,这样在常函数内就依旧能够修改。
#include<iostream>
using namespace std;
#include<string>
class person
{
public:
void show()const
{
age = 100;
}
mutable int age;
};
int main()
{
system("pause");
return 0;
}
2.常对象
1.定义
声明对象前加const
2.作用
1.属性不允许修改
#include<iostream>
using namespace std;
#include<string>
class person
{
public:
void show()const
{
age2 = 100;
}
int age1;
mutable int age2;
};
int main()
{
const person p;
p.age1 = 100;
system("pause");
return 0;
}
报错信息
原因:p.age=100;报错,不能进行修改