山芋粉丝 2019-05-15 12:03 采纳率: 0%
浏览 685

关于返回一个无名临时对象的问题?C++

以下有两个类,分别为Complex和Point。
Complex重载了+运算符,并返回一个临时无名对象;
Point重载了后置++运算符,为什么却不能像Complex那样返回一个临时无名对象呢?
【详细见以下代码注释行】

#include
using namespace std;

class Complex {
public:
Complex(double r = 0.0, double i = 0.0) :real(r), imag(i) {}
friend Complex operator+(const Complex &c1, const Complex &c2);
friend Complex operator-(const Complex &c1, const Complex &c2);
friend ostream &operator<<(ostream &out, const Complex &c);

private:
double real;
double imag;
};

Complex operator+(const Complex &c1, const Complex &c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag); //为什么这里可以返回一个临时的无名对象?
}

Complex operator-(const Complex &c1, const Complex &c2) {
return Complex(c1.real - c2.real, c1.imag - c2.imag);
}

ostream &operator<<(ostream &out, const Complex &c) {
cout << "(" << c.real << "," << c.imag << ")";

return out;

}

#include
#include
using namespace std;

//Point类定义
class Point {
public:
Point(int xx = 0, int yy = 0) {
x = xx;
y = yy;
}
Point(Point &p);
int getX() { cout << x << endl; return x; }
int getY() { cout << y << endl; return y; }
friend Point operator++(Point &p,int);

private:
int x, y;
};

Point::Point(Point &p) {
x = p.x;
y = p.y;
cout << "调用Point类的复制构造函数" << endl;
}

Point operator++(Point &p,int)
{
Point old;
old.x = p.x;
old.y = p.y;
p.x++;
p.y++;
return old;
//return Point(p.x++, p.y++);为什么这里不能返回一个临时无名对象?并且报错类Point没有适当的复制构造函数?
}

  • 写回答

2条回答 默认 最新

  • to be continue 2019-05-15 17:52
    关注

    第一种返回的old不会调用拷贝构造函数,第二种返回的会调用拷贝构造函数,拷贝构造函数的参数为类对象的引用,引用是不能引用临时变量

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!