this 指针
1.解决名称冲突
2,*this
指向本体,可以实现链式编程
#include<iostream>
using namespace std;
class person {
public:
person(int age) {
this->m_age = age;
}
person& personadd(person &p) {
//返回person的引用,不然后面创建p2返回时会创建一个新的p2',返回引用返回的还是p2
this->m_age += p.m_age;
return *this;
//返回本体
}
int m_age;
};
void test() {
person p1(18);
cout << p1.m_age << endl;
person p2(10);
p2.personadd(p1).personadd(p1);
//**实现链式编程**
cout << p2.m_age << endl;
}
int main() {
test();
system("pause");
return 0;
}
链式编程
this的本质时一个指针常量,指向不可以修改,值可以修改,在加上const后,可以限制值做变化`
class person{
void person()const{
this->m_b=10;
//m_b是可以修改的左值
};
int m_a;
mutable int m_b;
};`
创建对象使用mutable可以更改属性
const person p;
//创建常对象
常对象只能调用常函数