【问题标题】:Overloading doesn't work for <<重载不适用于 <<
【发布时间】:2015-06-21 03:17:06
【问题描述】:

我有这段代码,但我想不出重载

 ostream& operator<<(ostream& out)
     {int check=0;  
    node *temp;     
    temp=this->head->next;
    if(this->head->info==0)
        out<<"- ";  
    while(temp!=NULL)
        {   if(temp->info)
            {out<<temp->info<<" ";
            check=1;
        temp=temp->next;}
            else    if(temp->info==0&&check==1)
            {out<<temp->info<<" ";
                temp=temp->next;}
            else temp=temp->next;
        }
        return out;

    }

我在课堂上有一个结构,并希望输出一个大数字。大数是用链表创建的。重载方法在类内部,我收到错误:当我使用

时,运算符 cout<< B;

在main里面。

有关上述代码的更多详细信息。检查变量是为了确保像 00100 这样的数字打印为 100。如果 head->info ==0 number 为负数,如果为 1,则 number 为正数。我从 head->next 开始,因为第一个节点有数字符号。

【问题讨论】:

  • operator&lt;&lt; 重载不能是成员函数,如果您想要标准语法 - 您必须将其称为 B &lt;&lt; cout,这不是您所期望的。
  • 显然 'B

标签: c++ linked-list operator-overloading


【解决方案1】:

你做错了……在类中重载操作符让你可以使用类作为操作符的左操作数……所以基本上你现在可以做B &lt;&lt; cout;

您需要将运算符重载为函数在定义类的命名空间中,如下所示:

ostream& operator<<(ostream& out, TYPE_OF_YOUR_CLASS_HERE v)
{
    int check=0;  
    node *temp;     
    temp=b.head->next;
    if(v.head->info==0)
        out<<"- ";  
    while(temp!=NULL)
    {   
        if(v.info) {
            out<<v.info<<" ";
            check=1;
            temp=temp->next;
        } else if(temp->info==0&&check==1) {
            out<<temp->info<<" ";
            temp=temp->next;
        }
        else 
            temp=temp->next;
    }
    return out;
}

正如 Alper 建议的那样,您还需要使操作员

class MY_CLASS {
    ...
    friend ostream& operator<< (ostream& out, MY_CLASS v);
};

【讨论】:

  • 好的,所以,我把这个函数从课堂上拿了出来,我把它变成了朋友。唯一的问题是我有未声明的变量(node/temp 未在此范围内声明,并且 MY_CLASS 类没有名为 info 的成员。我认为这是因为我没有将函数放在您之前谈论的命名空间中。问题是......我不知道那是什么或要照顾什么。
  • 首先你的重载操作符需要和你的类型在同一个命名空间中。您还需要在源代码中包含您正在使用的所有头文件和命名空间 usings:using namespace YOUR_NAMESPACE; 用于代码中使用的所有命名空间。
【解决方案2】:

如果您希望允许类类型恰好位于二元运算符右侧的表达式,则首选全局 operator&lt;&lt; 重载。

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const YourClassType&amp; B)

另外,如果它需要访问私有成员,请将其设为friend。否则,只需使其成为非朋友非成员函数。

【讨论】:

    【解决方案3】:

    operator&lt;&lt; 重载不能是成员函数,如果您想要标准语法 - 您必须将其称为 B &lt;&lt; cout,这可不是很好。
    (对于所有二元运算符,B.operator&lt;&lt;(cout) 表示B 是左侧。)

    这是我通常做的事情。

    一个命名的常规成员函数:

    ostream& output(ostream& out) const
    {
        // Your code here.
    }
    

    和一个只调用它的运算符:

    ostream& operator<<(ostream& os, const MyClass& c) 
    { 
        return c.output(os); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 2021-11-08
      • 1970-01-01
      • 2020-06-20
      相关资源
      最近更新 更多