运算符重载问题?

时间:2015-09-11 23:29:10

标签: c++ overloading operator-keyword

我在此代码中包含七个错误,包含运算符重载问题,我尝试在>>上执行运算符重载和<<并且它没有工作

#include<iostream>
using namespace std;
class complex
{
private:
    double re,im;
public:
    complex(double a=0.0,double b=0.0)
    {re=a;im=b;}
    friend istream& operator>>(istream&,complex&);
    friend ostream& operator<<(ostream&,complex&);
};
istream& operator>>(istream& s,complex& cc2)
{
    cout<<"Enter real part:";
    s>>cc2.re;
    cout<<"Enter imaginary part:";
    s>>cc2.im;
    return s;
}
ostream& operator<<(ostream& t,complex& cc2)
{
    t<<"The real part="<<cc2.re<<endl;
    t<<"The imaginary part="<<cc2.im<<endl;
    return t;
}
int main()
{
    complex c1,c2(2.4,3.8);
    cin>>c1;
    cout<<c1;
    cout<<c2;
    return 0;
}

2 个答案:

答案 0 :(得分:0)

代码“按原样”为我工作。不确定您使用的是哪个平台,但由于这是C ++代码,请确保您使用 C ++ 的编译器而不是 C

这是我的GNU / Linux终端的输出(将代码放在文件test.cpp中):

➜  /tmp  g++ test.cpp -o test
➜  /tmp  ./test
Enter real part:4
Enter imaginary part:5
The real part=4
The imaginary part=5
The real part=2.4
The imaginary part=3.8

不加修改地工作。

答案 1 :(得分:0)

使用g++ 4.9.2clang++-4.7clang++-4.6在GNU / Linux上工作。似乎是一个编译器错误。

您可以尝试更新到更新版本的VC ++。

相关问题