C++ Reference [Talk about the return value problem again]

Directly on the code:

class Person
{
public:

	Person(int age)
	{
		//1、当形参和成员变量同名时,可用this指针来区分
		this->age = age;
	}

	Person PersonAddPerson(Person p)
	{
		this->age += p.age;
		//返回对象本身
		return *this;
	}

	int age;
};

 We run:

    Person p(10);
	Person p2(15);
	p2.PersonAddPerson(p).PersonAddPerson(p);
	cout << p2.age;

The answer is 25.

Let's take a look at the function execution process:

First, p2 calls the function PersonAddPerson(p),

In the process of calling, p2 adds the age of p to his own age, which becomes 25;

Because we still need to use the. Symbol to call this function,

So the return value must be a Person type.

So at this time, p2.PersonAddPerson(p), as an lvalue Person, we call it P3, he and P2 have exactly the same age, but he is a copy of P2.

When the function is called again, it is called by P3.

In other words, after calling it twice, the value of that virtual P3 becomes 35, and then a copy of P3 that becomes 35 is copied, and a P4 appears.

So the value of P2 is still 25 at this time.

To solve this problem, we need to turn the return value into a reference type:

Person& PersonAddPerson(Person p)
	{
		this->age += p.age;
		//返回对象本身
		return *this;
	}

In this way, P2 is returned every time.

 

 

Guess you like

Origin blog.csdn.net/Kukeoo/article/details/114957078