开发者社区> 问答> 正文

关于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;
}

展开
收起
a123456678 2016-03-04 18:24:12 4031 0
4 条回答
写回答
取消 提交回答
  • https://www.runoob.com/cplusplus/cpp-overloading.html

    2020-08-03 20:11:24
    赞同 展开评论 打赏
  • 乐于学习与分析

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

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

    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;
    };

    2019-07-17 18:52:43
    赞同 展开评论 打赏
问答分类:
C++
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载

相关实验场景

更多