“return”:无法从“Complex”转化为“Complex &”

一、参考资料

二、问题描述

在进行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了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值