【问题标题】:Why cout is not working in the friend function that overloads the operator << which is an istream operator为什么 cout 不能在重载运算符 << 这是 istream 运算符的友元函数中工作
【发布时间】:2019-02-14 07:24:23
【问题描述】:

为什么cout 不能在重载 C++ 的 istream 运算符的函数中工作(&gt;&gt;)?我应该怎么做才能让它工作?

在这一行:cout &gt;&gt; "Enter x and y: " 显示错误?

为什么?
我该如何解决?

这是overload &gt;&gt;operator &lt;&lt; 的代码

#include<iostream>

using namespace std;

class myClass
{
    int x,y;
public:
    myClass(int a,int b)
    {
        x=a;y=b;
    }
    friend istream &operator>>(istream &in, myClass &ob);
    friend ostream &operator<<(ostream &out, myClass ob);
};
istream &operator>>(istream &in,myClass &ob)
{
    cout >> "Enter x and y: ";
    in >> ob.x;
    in >> ob.y;
    return in;
}
ostream &operator<<(ostream &out,myClass ob)
{
    out << ob.x << " " << ob.y << endl;
}
int main()
{
    myClass ob(10,20);
    cout << ob;
    cin >> ob;
    cout << ob;
}

【问题讨论】:

  • 在询问有关错误的问题时,请始终包括您遇到的实际错误。将它们(作为文本)完整地复制粘贴到问题中。然后在代码中添加 cmets 以显示错误发生的位置。另外请花一些时间阅读how to ask good questionsthis question checklist
  • cout 是一个输出流,所以支持&lt;&lt; 但不支持&gt;&gt;。您正在使用无效的&gt;&gt;。投票结束,因为这本质上是一个错字(修复两个字符)。此外,将输出操作放在operator&gt;&gt;() 的实现中并不是一个好主意——就流而言,从一个流读取应该独立于写入另一个流。而是在使用operator&gt;&gt;() 之前编写提示。如果要提示输入,请编写一个单独的函数来提示一个流并从另一个流中读取。
  • &gt;&gt; 运算符不应该以任何方式与用户交互。假设你想从一个文件中读取一堆对象——你真的希望你的程序在每次读取其中一个对象时打印一个提示吗?
  • 你的重载是无关紧要的; int main() { cout &gt;&gt; "Enter x and y: ";} 也会遇到同样的问题。阅读minimal reproducible example

标签: c++ operator-overloading cout istream


【解决方案1】:

你的错误是你混淆了&lt;&lt;&gt;&gt;cout&gt;&gt;"Enter x and y: ";应该是cout &lt;&lt; "Enter x and y: ";

此外,在过载的operator&gt;&gt; 中提示用户也不是很好的风格。如果您的&gt;&gt; 被用于读取文件怎么办?那时您不想提示用户。所以把cout&lt;&lt;"Enter x and y: ";移到它所属的主函数中。

这样

istream &operator>>(istream &in,myClass &ob)
{
    in>>ob.x;
    in>>ob.y;
    return in;
}

int main()
{
    myClass ob(10,20);
    cout<<ob;
    cout<<"Enter x and y: ";
    cin>>ob;
    cout<<ob;
    return 0;
}

【讨论】:

  • 这不会编译,因为它仍然包含cout&gt;&gt;""
  • @AlanBirtles 抱歉,已修复。
猜你喜欢
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
相关资源
最近更新 更多