0

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

重载运算符“>>”的使用不明确(操作数类型为“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;

}
//------------------------------------------------
4

1 回答 1

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&)。

于 2012-11-11T00:44:30.320 回答