C++中函数 返回值和返回引用的探讨

C++中函数返回值和返回引用的探讨

看C++教程返回引用和返回值没搞清楚,后来自己添加代码验证,这里通过自定义构造函数和析构函数输出验证。

首先是类中成员函数返回引用的代码:

#include <stdio.h>
#include <string>
#include <iostream>

using namespace std;

class Person
{
public:

	Person()
	{
		cout << "默认构造函数" << endl;
	}
	
	Person(int age)
	{
		//1、当形参和成员变量同名时,可用this指针来区分
		cout << "有参构造函数" << endl;
		this->age = age;
	}

	Person(const Person& p) {
		age = p.age;
		cout << "拷贝构造函数!" << endl;
	}


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

	~Person()
	{
		cout << "析构函数调用" << endl;
	}
	int age;
};

void test01()
{
	Person p1(10);
	cout << "p1.age = " << p1.age << endl;

	Person p2(10);
	p2.PersonAddPerson(p1).PersonAddPerson(p1).PersonAddPerson(p1);
	cout << "p2.age = " << p2.age << endl;
}

int main() {

	test01();

	system("pause");

	return 0;
}

输出结果:

再看返回值的代码:

#include <stdio.h>
#include <string>
#include <iostream>
#include "point.h"
#include "circle.h"

using namespace std;

class Person
{
public:

	Person()


	{
		cout << "默认构造函数" << endl;
	}
	
	Person(int age)
	{
		//1、当形参和成员变量同名时,可用this指针来区分
		cout << "有参构造函数" << endl;
		this->age = age;
	}

	Person(const Person& p) {
		age = p.age;
		cout << "拷贝构造函数!" << endl;
	}


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

	~Person()
	{
		cout << "析构函数调用" << endl;
	}
	int age;
};

void test01()
{
	Person p1(10);
	cout << "p1.age = " << p1.age << endl;

	Person p2(10);
	p2.PersonAddPerson(p1).PersonAddPerson(p1).PersonAddPerson(p1);
	cout << "p2.age = " << p2.age << endl;
}

int main() {

	test01();

	system("pause");

	return 0;
}

输出结果:

从两个输出结构来看,返回引用比返回值少创建了三个对象,因此可以理解为,当函数返回值时,系统会临时复制一个对象使用。而返回引用时,不会这样操作。

posted @ 2021-12-08 21:36  _xiao_hu  阅读(580)  评论(0)    收藏  举报