#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
this->m_Age = age;
}
//常函数 : 修饰成员函数中的 this指针,让指针指向的值不可以修改
//常函数,等于用const修饰this 指向的值,限定它是只读的
void showPerson() const
{
//m_Age = 100;
m_A = 100;
//this指针的本质 const Person * const this
//前const:指针指向的值不能改 后const:指针的指向不允许修改了
//this = NULL;指针的指向不可以修改,而指针指向的值可以修改
cout << "person age = " << this->m_Age << endl;
}
void func()
{
m_Age = 100;
cout << "func调用" << endl;
}
int m_Age;
mutable int m_A; //常函数中 或者常对象中 有些特殊的属性依然想修改 加入关键字 mutable
};
void test01()
{
//常对象
const Person p1(10);
//p1.m_Age = 10;//不能修改常对象以及它的属性
p1.m_A = 10;//因为有特殊的声明,所有可以改掉。
p1.showPerson();
//p1.func(); //常对象不能修改里面的属性,但是在普通的函数里可以把age改掉,常对象只能调用常函数。
//可以间接修改
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
肆-拾陆|常函数和常对象
最新推荐文章于 2024-07-22 10:02:43 发布