C++ this指针的具体用法
#本人想记录自己在学习c++的过程,以备在以后的学习期间方便进行回顾查看!
this 指针的功能主要有两种: 1.解决名称冲突 2.返回 对象本身*this 首先我们先创建一个简单的类:person
#include <iostream>
using namespace std;
#include <string>
class person
{
public:
person(int age,string name)
{
m_age=age;
this->name=name;
}
person& addPersonAge(person &p)
{
this->m_age+=p.m_age;
return *this;
}
int m_age;
string name;
};
void test01()
{
person p1(23,"张三");
cout<<"p1的年龄为:"<<p1.m_age<<endl;
cout<<"p1的姓名为:"<<p1.name<<endl;
}
void test02()
{
person p2(18,"李四");
cout<<"p2的年龄为:"<<p2.m_age<<endl;
cout<<"p2的姓名为:"<<p2.name<<endl;
person p3(15,"王五");
p3.addPersonAge(p2);
cout<<"p3的年龄为:"<<p3.m_age<<endl;
p3.addPersonAge(p2).addPersonAge(p2).addPersonAge(p2);
cout<<"p3的年龄为:"<<p3.m_age<<endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
这是运行的结果,虽然简单但是值得记录!
|