Class and object-this pointer

Class and object-this pointer

1. When the formal parameter and the member variable have the same name, they can be distinguished by the this pointer.
2. To return the object itself in the non-static member function of the class, return * this can be used

#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;
}

Guess you like

Origin blog.csdn.net/qq_54673833/article/details/114004057