c++返回引用的好处

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huhuandk/article/details/84986746

在c++中,函数返回引用,可以减少拷贝构造函数的调用次数,提高效率。

#include <iostream>

using  namespace std;
class C1
{
private:
	int a;
	int b;
public:
	C1(int a=0,int b=0)  //构造函数
	{
		this->a = a;
		this->b = b;

		cout << "c1构造函数" << a << endl;
	}
	C1(const C1 &t)  //拷贝构造函数
	{
		this->a = t.a;
		this->b = t.b;
		cout << "拷贝构造函数" << endl;
	}
	~C1()   //析构函数
	{
		cout << "c1析构函数" << a << endl;
	}
	int geta()
	{
		return this->a;
	}
	int getb()
	{
		return this->b;
	}
	void print()  //输出值
	{
		cout << "a:" << this->a << "\t" << "b:" << this->b << endl;
	}
	C1&add1(C1 &t)  //求加法,返回引用
	{
		this->a = this->a + t.geta();
		this->b = this->b + t.getb();
		return *this;
	}
	C1 add2(C1 &t)
	{
		C1 temp(this->a + t.geta(), this->b + t.getb());

		return temp;
	}
};

int main()
{
	C1 a(1, 2);
	C1 b(2, 3);
	a.add1(b);
	a.print();
	//a = a.add2(b);
	//a.print();
	return 0;
}

返回引用结果:

不返回引用结果:

由此可见,返回引用比不返回引用少调用了一次拷贝构造函数 。

猜你喜欢

转载自blog.csdn.net/huhuandk/article/details/84986746
今日推荐