类和对象-this指针

类和对象-this指针

1、当形参和成员变量同名时,可用this指针区分
2、在类的非静态成员函数中返回对象本身,可用return * this

#include<iostream>
using namespace std;
class person
{
    
    
public:
	person(int age)//构造函数
	{
    
    
		this->age = age;
	}
	int age;
	person& personaddage(person &p)
	{
    
    
		this->age += p.age;
		//this是指向p2的指针,而*this就是指向的这个p2的对象的本体
		return *this;
	}
};
void test01()//解决名称冲突
{
    
    
	person p1(233);
	cout << "p1年龄为 " << p1.age << endl;
}
void test02()
{
    
    
	person p1(13);
	person p2(17);
	p2.personaddage(p1).personaddage(p1).personaddage(p1) ;
	cout << "p2年龄为 " << p2.age << endl;
}
int main()
{
    
    
	test01();
	test02();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_54673833/article/details/114004057