关于c++运算符重载总是有错误-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

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

a123456678 2016-03-04 18:24:12 1622

在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;
}
C++
分享到
取消 提交回答
全部回答(4)
  • 游客duzwdtzqsaq3i
    2020-08-03 20:11:24

    https://www.runoob.com/cplusplus/cpp-overloading.html

    0 0
  • xumaojun
    2019-07-17 18:52:43

    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}
    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}
    类的定义分号结束。分号是必需的,因为在类定义之后可以接一个对象定义列表。定义必须以分号结束:

    0 0
  • nothingfinal
    2019-07-17 18:52:43

    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}
    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}
    类的定义分号结束。分号是必需的,因为在类定义之后可以接一个对象定义列表。定义必须以分号结束:

    0 0
  • a123456678
    2019-07-17 18:52:43

    参考代码如下:
    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;
    };

    0 0
添加回答
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题
推荐课程