2 u013340360 u013340360 于 2014.07.05 01:55 提问

关于c++运算符重载总是有错误

在visual studio 2010 上 重载运算符<<输出复数
代码如下
#include
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator +(Complex &c2);
friend ostream& operator<<(ostream&os,Complex&);
private:
double real;
double imag;
}
ostream &operator<<(ostream &output,Complex&c)
{
output<<c.real<<c.imag<<endl;
return output;
}
Complex Complex::operator+(Complex &c2)
{
return Complex(real+c2.real,imag+c2.imag);
}
int main()
{
Complex c1(2,4),c2(2,5),c3;
c3=c1+c2;
cout<<c3;
return 0;
}
这个代码是我照书上敲下来的 ,但是怎么运行都有错误
求大神帮忙

2个回答

ComputerInBook
ComputerInBook   2014.07.08 17:05

两个问题:1. 少头文件#include <iostream>;2 类定义的花括号}后少一个分号(;).

caoqiwen2001
caoqiwen2001   2014.07.22 20:13

class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator +(Complex &c2);
friend ostream& operator<<(ostream&os,Complex&);
private:
double real;
double imag;
};
类后面的分号没有加上去,大哥。仔细调试。

Csdn user default icon
上传中...
上传图片
插入图片