一、参考资料
二、问题描述
在进行C++作业中遇到了“return”:无法从“Complex”转化为“Complex &”此类问题。
作业题目:
面对对象程序设计之运算符重载(1)定义一个复数类Complex,重载运算符“+”使之能用于复数的加法运算。将运算符函数重载为非成员、非友元的普通函数。编写程序,求两个复数之和。
自己做的代码如下:
#include<iostream>
using namespace std;
class Complex {
public:
Complex() { real = 0; imag = 0; }
Complex(double r, double i) { real = r; imag = i; }
friend Complex& operator + (Complex & c1, Complex & c2);
void display();
private:
double real; double imag;
};
void Complex::display() {
if (imag>=0)
cout << "(" << real << "+" << imag << "I)" << endl;
else
cout << "(" << real << imag << "I)" << endl;
}
Complex& operator+(Complex& c1, Complex& c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
int main() {
Complex c1(3, 4), c2(5, 6),c3;
c3 = c1 + c2;
cout << "c1="; c1.display();
cout << "c2="; c2.display();
cout << "c3="; c3.display();
return 0;
}
三、出错原因
暂时无法找到。
四、解决方案
不过,查找书籍发现在友元函数定义那一块有点缺点,于是进行修改
class Complex {
public:
Complex() { real = 0; imag = 0; }
Complex(double r, double i) { real = r; imag = i; }
friend Complex operator + (Complex c1, Complex c2);
void display();
private:
double real; double imag;
};Complex operator+(Complex c1, Complex c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag);}
这样return就能返回同类型的Complex了。