【问题标题】:Ambiguous Overload For operator "<<"运算符“<<”的模糊重载
【发布时间】:2019-08-11 06:26:15
【问题描述】:

我正在学习 C++ 中的运算符重载,我想知道以下代码的输出

#include<iostream>
using namespace std;
class xyz
{

 public:
        int i;

    friend ostream & operator<<( ostream & Out , int);
};



ostream & operator<<(ostream & out , int i)
{
    cout<<10+i<<endl;
}


int main()
{
    xyz A;
    A.i=10;

    cout<<10;
}

我有两个错误

  1. 错误:“运算符

  2. 错误:“运算符

谁能解释一下是什么问题?

我想知道,如果我重载一个“

【问题讨论】:

  • int 加上您提供的那个已经超载。你想用代码实现什么?如果您想输出xyz,那么您可能想为该类型编写重载,而不是为其成员编写重载
  • 我很好奇。假设您可以用您自己的替换the library provided overload,您如何期望cout&lt;&lt;10+i&lt;&lt;endl; 在没有终止的情况下不递归?
  • 还应该有行号和文件名(如果使用好的 IDE,还应该有导航)。你可以检查有两个定义。
  • tbh 很难回答你的问题,因为它并不清楚为什么不应该有歧义;)。如果您解释为什么您认为必须为int 编写&lt;&lt; 重载,也许问题会更清楚
  • 你不能只是放随机代码并期望它工作,看起来你不知道你在做什么。似乎您尝试效仿一个示例,但是对于 xyz 而不是 int 而言,运算符会被重载

标签: c++ operator-overloading


【解决方案1】:

所以很明显,问题是你已经写了ostream &amp; operator&lt;&lt;(ostream &amp; out , int i),而这已经存在。但是很明显你要写的是这个

ostream& operator<<(ostream& out, const xyz& a) // overload for xyz not int
{
    out<<a.i<<endl; // use out not cout
    return out;     // and don't forget to return out as well
}

还有这个

int main()
{
    xyz A;
    A.i=10;

    cout<<A<<endl; // output A not 10
}

【讨论】:

    【解决方案2】:
    
    // this include brings std::ostream& operator<<(std::ostream&, int)
    // into scope and therefore you cannot define your own later
    #include<iostream>  
    
    using namespace std;
    class xyz
    {
    
     public:
            int i;
    
        // needs body 
        friend ostream & operator<<( ostream & Out , int)
        {
            return Out;
        }
    };
    
    
    
    /* cant have this after including ostream
    ostream & operator<<(ostream & out , int i)
    {
        cout<<10+i<<endl;
    }
    */
    
    
    int main()
    {
        xyz A;
        A.i=10;
    
        cout<<10;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 2022-10-01
      • 1970-01-01
      相关资源
      最近更新 更多