gpt4 book ai didi

c++ - 重载运算符 '>>' 的使用不明确(操作数类型为 'istream'(又名 'basic_istream')和 'MyIncreEx')

转载 作者:行者123 更新时间:2023-11-28 00:52:30 27 4
gpt4 key购买 nike

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

重载运算符“>>”的使用不明确(操作数类型为“istream”(又名“basic_istream”)和“MyIncreEx”)

我看不出它有什么模棱两可的地方:

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);
friend MyIncreEx operator++(MyIncreEx& d);

public:
int num1 = 0, num2 = 0, num3 = 0;
};

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)
{
d.num1++;
d.num2++;
d.num3++;
return d;
};

MyIncreEx operator++(MyIncreEx& d, int dummy)
{
d.num1++;
d.num2++;
d.num3++;
return d;
};

int main()
{
MyIncreEx obj;

cout << "please enter three numbers: ";
cin >> obj;

cout << "The original value are: " << obj << endl;
obj++;

cout << "The new values after obj++ are: " << obj << endl;
++obj;

cout << "The new values after ++obj are: " << obj << endl;
}

最佳答案

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

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

关于c++ - 重载运算符 '>>' 的使用不明确(操作数类型为 'istream'(又名 'basic_istream<char>')和 'MyIncreEx'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13327539/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com