使用重载运算符'&gt;&gt;'是不明确的(操作数类型'istream'(又名'basic_istream <char>')和'MyIncreEx')</char>

时间:2012-11-11 00:40:53

标签: c++ operator-overloading ambiguous

这是代码,我似乎没有发现它有什么问题;我需要重载&lt;&lt;和&gt;&gt;运算符,但我收到以下错误:

使用重载运算符'&gt;&gt;'是不明确的(操作数类型'istream'(又名'basic_istream')和'MyIncreEx')

我看不出它真的含糊不清:

#include<iostream>
using namespace std;


class MyIncreEx;
istream& operator>>(istream& is, MyIncreEx& s);
ostream& operator<<(ostream &os, MyIncreEx& s);
MyIncreEx operator++(MyIncreEx& d, int dummy);
MyIncreEx operator++(MyIncreEx& d);

class MyIncreEx
{
friend istream& operator>>(istream& is, MyIncreEx s);
friend ostream& operator<<(ostream& os, MyIncreEx s);
friend MyIncreEx operator++(MyIncreEx& d, int dummy);   //post-fix ex: x++;
friend MyIncreEx operator++(MyIncreEx& d);  //pre-fix ex: ++x;

public:
MyIncreEx(){num1=0; num2=0; num3=0;};

int num1;
int num2;
int num3;
};

//------------------------------------------------
istream& operator>>(istream& is, MyIncreEx& s)
{
is >> s.num1;
is >> s.num2;
is >> s.num3;
return is;
};

//------------------------------------------------
ostream& operator<<(ostream &os, MyIncreEx& s)
{
os << "(" << s.num1 <<"," <<s.num2 << "," << s.num3 <<")"<< endl;
return os;
};

//------------------------------------------------
MyIncreEx operator++(MyIncreEx& d)              //pre-fix   ex: ++x;
{
d.num1=d.num1+1;
d.num2=d.num2+1;
d.num3=d.num3+1;

return d;
};
//------------------------------------------------

MyIncreEx operator++(MyIncreEx& d, int dummy)   //post-fix ex: x++;
{
d.num1=d.num1+1;
d.num2=d.num2+1;
d.num3=d.num3+1;
return d;
};

//------------------------------------------------
int main()
{
MyIncreEx obj;

cout << "please enter three numbers: ";
cin  >> obj;
cout << "The original value are: ";
cout << obj;
cout << endl;
obj++;
cout << "The new values after obj++ are: ";
cout <<  obj;
cout << endl;
++obj;
cout << "The new values after ++obj are: ";
cout << obj;
cout << endl;

}
//------------------------------------------------

1 个答案:

答案 0 :(得分:3)

您声明了两个不同版本的输出运算符:

istream& operator>>(istream& is, MyIncreEx& s);
ostream& operator<<(ostream &os, MyIncreEx& s);

class MyIncreEx
{
    friend istream& operator>>(istream& is, MyIncreEx s);
    friend ostream& operator<<(ostream& os, MyIncreEx s);
    ...
};

friend运算符具有不同且冲突的签名。你可能想把它们声明为

    friend istream& operator>>(istream& is, MyIncreEx& s);
    friend ostream& operator<<(ostream& os, MyIncreEx const& s);

(假设您还修复了输出运算符以使用MyIncreEx const&而不是MyIncreEx&)。