重载运算符<<

时间:2016-02-07 21:23:12

标签: c++ operator-overloading

我有BigInt类的以下代码,我正在尝试重载operator<<

class BigInt
{
private:
    int numDigits;
    char vals[];

public:        
    friend std::ostream& operator <<( std::ostream& os , const BigInt &param );
};


std::ostream& BigInt::operator <<( std::ostream& os , const BigInt & param )
{
    os <<" number of the bits is " <<param.numDigits << " and it`s   valeuris" <<param.vals<<"\ n ";
    return os;
};

我一直收到这个错误:

  

xxxxx必须只接受一个参数。

我在这个错误上搜索了很多。我知道我应该在课堂上让operator<<成为朋友的功能,或者在课堂上宣布它,我也关注运算符<<的返回。很奇怪,无论哪种方式我都会收到错误。

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

我认为这里的问题是你(可能是无意中)混合和匹配两种不同的方法。

写作时

friend std::ostream& operator <<( std::ostream& os , const BigInt &param );

在类定义中,您说将有一个名为operator <<自由函数,它包含ostreamBigInt。当你写

std::ostream& BigInt::operator <<( std::ostream& os , const BigInt & param )
{
    ...
};

您正在定义名为BigInt的{​​{1}}的成员函数,其中包含两个参数。这两个参数与隐式operator <<指针相结合,最多可添加三个参数 - 超出您的预期。请注意,虽然此函数名为this,但它您在类定义中声明为operator<<的{​​{1}}。

要解决此问题,您有几个选择。首先,当您定义operator<<时,可以省略friend前缀,这将解决问题。或者,将您的实现与类定义中的operator<<定义结合起来:

BigInt::
相关问题