以下有两个类,分别为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没有适当的复制构造函数?
}