重载 operator<< 时出现 "operator<< must take exactly one argument" 形式的错误

Getting an error of the form "operator<< must take exactly one argument" when overloading operator<<

我有以下用于 BigInt class 的代码,我正在尝试重载 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 must take exactly one argument.

我对这个错误进行了很多搜索。我知道我应该在 class 中使 operator<< 成为一个友元函数或者在 class 之外声明它,并且我还关心了运算符 << 的 return .太奇怪了,无论哪种方式我都会出错。

谁能帮帮我?

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

写的时候

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

在 class 定义中,您是说将有一个名为 operator << 自由函数 接受 ostreamBigInt。当你写

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

您正在定义一个名为 operator <<BigInt 成员函数 ,它有两个参数。这两个参数与隐式 this 指针相结合,加起来最多三个参数 - 比您预期的要多。请注意,尽管此函数称为 operator<<,但它 不是 您在 class 定义中声明为 friendoperator<<

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

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