以下有两个类,分别为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没有适当的复制构造函数?
}
第一种返回的old不会调用拷贝构造函数,第二种返回的会调用拷贝构造函数,拷贝构造函数的参数为类对象的引用,引用是不能引用临时变量
造成问题的原因是:
Complex类没有复制构造函数,有构造函数Complex(double r = 0.0, double i = 0.0) :real(r), imag(i) {}。
Point类有复制构造函数Point(Point &p);,和构造函数Point(int xx = 0, int yy = 0) 。
所以,
return Complex(c1.real + c2.real, c1.imag + c2.imag);返回时调用了该类的构造函数。
return Point(p.x++, p.y++);返回时,由于该类的构造函数和复制构造函数同名,也许造成编译器无法识别???(我也不懂为什么会这样),所以报错的吧……
Complex operator+(const Complex &c1, const Complex &c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag); //为什么这里可以返回一个临时的无名对象?
}
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没有适当的复制构造函数?
}