C++返回对象与引用
其实,大家在写C++代码的时候,都会发现,有些函数的返回是引用,有些函数发的返回是对象,今天我们一起来做一下区分。
1.根源
返回对象和返回引用的最主要的区别就是函数原型和函数头
看一下例子:
Test get(const Test&) //返回对象
Test& get(const Test&) //返回引用
2.操作性
这里的操作性指的是在返回的过程中,函数会进行哪些操作
-
返回对象:返回对象调用了复制构造函数,所以在时间上面,返回对象的时间时间成本包括了复制构造函数来生成副本所需的时间和调用析构函数删除副本所需的时间 ,而返回对象其实是调用了程序的副本。直接返回对象与按值传递对象类似 ,都是临时的副本。
-
返回引用:返回引用与按引用传递对象类似,调用和被调用的函数对同一个对象进行操作,所以不存在副本,从空间上,节省了空间;没有了拷贝构造函数的调用,从时间上,节省了时间成本。
Test& Test::operator++() { ts++; return *this; } Test Test::operator++(int) { Test temp(tt); //创建对象 tt++; return Test; //返回对象的副本 }
3.返回的时机
所谓返回的时机,就是什么时候可以返回对象,什么时候可以返回引用。
- 如果函数返回的是通过引用或指针传递给它的对象,则应当按引用返回对象 ,当按引用返回调用函数的对象或作为参数传递给函数的对象 ;如:Test& Test::operator++()
- 如果函数返回在函数中创建的临时对象,则不要使用引用,如果先创建一个对象,然后返回改对象的副本,则可以使用返回对象 ;如:Test Test::operator++(int)
4.例子
- 返回引用
#include <iostream>
using namespace std;
class Complex {
public:
Complex(float x = 0, float y = 0) :_x(x), _y(y) {}
void dis() {
cout << "(" << _x << "," << _y << ")" << endl;
}
const Complex& operator+(const Complex &another);
private:
float _x;
float _y;
};
const Complex& Complex::operator+(const Complex & another) {
return Complex(this->_x + another._x, this->_y + another._y);
}
int main()
{
Complex c1(3, 3);
Complex c2(4, 4);
c1.dis();
c2.dis();
Complex c3 = c1 + c2;
c3.dis();
system("pause");
return 0;
}
- 返回对象
#include <iostream>
using namespace std;
class Complex {
public:
Complex(float x = 0, float y = 0) :_x(x), _y(y) {}
void dis() {
cout << "(" << _x << "," << _y << ")" << endl;
}
const Complex operator+(const Complex &another);
private:
float _x;
float _y;
};
const Complex Complex::operator+(const Complex & another) {
//return Complex(this->_x + another._x, this->_y + another._y);
Complex com;
com._x = this->_x + another._x;
com._y = this->_y + another._y;
return com;
}
int main()
{
Complex c1(3, 3);
Complex c2(4, 4);
c1.dis();
c2.dis();
Complex c3 = c1 + c2;
c3.dis();
system("pause");
return 0;
}
想了解学习更多C++后台服务器方面的知识,
请关注: 微信公众号:C++后台服务器开发
本文详细解析了C++中返回对象与返回引用的区别,包括它们的根源、操作性、返回时机及具体实例,帮助读者理解如何在不同场景下选择合适的返回方式。
1152

被折叠的 条评论
为什么被折叠?



