错误:没有运算符<<与这些操作数匹配?

Error: No operator << matches these operands?

本文关键字:lt 操作数 运算符 错误      更新时间:2023-10-16

我正在练习一些c++(试图离开Java),我偶然发现了这个恼人的错误:错误:No operator <<匹配这些操作数。我在这个网站上搜索了一个明确的答案,没有运气,我确实发现我不是唯一一个。

这个错误在我的。cpp文件中,还有其他错误,但我现在没有注意到它们。

void NamedStorm::displayOutput(NamedStorm storm[]){
    for(int i = 0; i < sizeof(storm); i++){
        cout << storm[i] << "n";
    }
}

"<<"有点问题,我不知道是怎么回事。

由于您正在尝试cout一个类对象,您需要重载<<

std::ostream& operator<<(ostream& out, const NamedStorm& namedStorm)

必须重载<<操作符才能将对象重定向到流中。

您可以作为成员函数重载,但是在这种情况下,您必须使用object << stream语法才能使用重载的函数。

如果你想使用stream << object语法,那么你必须重载<<操作符作为一个'free'函数,也就是说,不是你的NamedStorm类的成员。

下面是一个工作示例:

#include <string>
#include <iostream>
class NamedStorm
{
public:
    NamedStorm(std::string name)
    {
        this->name = name;
    }
    std::ostream& operator<< (std::ostream& out) const
    {
        // note the stream << object syntax here
        return out << name;
    }
private:     
    std::string name;
};
std::ostream& operator<< (std::ostream& out, const NamedStorm& ns)
{
   // note the (backwards feeling) object << stream syntax here
   return ns << out;
}
int main(void)
{
    NamedStorm ns("storm Alpha");
    // redirect the object to the stream using expected/natural syntax
    std::cout << ns << std::endl;
    // you can also redirect using the << method of NamedStorm directly
    ns << std::cout << std::endl;
    return 0; 
}

从自由重定向重载中调用的函数必须是NamedStorm的公共方法(在本例中我们调用的是NamedStorm类的operator<<方法),或者重定向重载必须是NamedStorm类的friend,以便访问私有字段