- 一、const修饰的成员函数
- 二、const修饰的常对象
-
使用const修饰的成员函数时,const修饰this指针指向的内存区域,成员函数体内不可以修改本类中的任何普通成员变量
-
当成员变量类型符前使用mutable修饰时除外
#include
using namespace std;
class Maker {
Maker(int id, int age)
{
this->id = id;
this->age = age;
}
// 常函数 成员函数后面添加const 该函数就是常函数
void printMaker()const
{
}
public:
int id;
int age;
};
- 函数的后面添加const 该函数是常函数
- 常函数内部不可以修改普通成员变量
- const修饰的是this指针指向的空间中的变量不能修改
- mutable修饰的成员变量在常函数中可以进行修改
#include
using namespace std;
class Maker {
Maker(int id, int age)
{
this->id = id;
this->age = age;
this->score = 100;
}
// 常函数 成员函数后面添加const 该函数就是常函数
void printMaker()const
{
score = 100;// mutable修饰的成员变量在常函数中可以进行修改
cout << "mutable修饰的变量" << score << endl;
}
public:
int id;
int age;
mutable int score;
};
void test01()
{
Maker m(1,2);
m.printMaker();
}
int main()
{
return EXIT_SUCCESS;
}
二、const修饰的常对象
在数据类型前面加上const,让对象成为常对象
- 常对象不能改变普通成员变量的值
- 常对象不能调用普通成员函数
- 常对象可以调用常函数
- 常对象可以修改Mutable修饰的变量
- 普通对象也可以调用常函数
#include
using namespace std;
class Maker {
public:
Maker(int id, int age)
{
this->id = id;
this->age = age;
this->score = 100;
}
// 常函数 成员函数后面添加const 该函数就是常函数
void printMaker()const
{
score = 100;// mutable修饰的成员变量在常函数中可以进行修改
cout << "mutable修饰的变量" << score << endl;
}
void func()
{
cout << "xxx" << endl;
}
public:
int id;
int age;
mutable int score;
};
void test01()
{
// 在数据类型前面加上const让对象成为常对象
const Maker m(1,8);
//m.id =1;// 常对象不能修改普通成员变量的值
//m.func();// 常对象不可以调用普通的成员函数
m.printMaker();// 常对象可以调用常函数
m.score = 500;// 常对象可以修改mutable修饰的成员变量
}
int main()
{
return EXIT_SUCCESS;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)