错误:没有运算符<<与这些操作数匹配?
Error: No operator << matches these operands?
我正在练习一些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
,以便访问私有字段
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 控制允许动态运行c++的并发操作数
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- <<操作员在下面的行中工作
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- C++ 带有向量的 IF 计算操作数
- 是否所有C++运算符都接受操作数?
- 一元*运算符的操作数是否期望一个 prvalue
- 与'operator='不匹配(操作数类型'String'且"void")
- 不正确的操作数类型 MSVC
- C2678 二进制 '==':未找到采用 'Card' 类型左操作数的运算符(或者没有可接受的转换)
- 错误:类型"double()"和"double()"的操作数无效到二进制&quo
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- 没有运算符"="与这些操作数匹配,JUCE 窗口演示应用程序
- 如果我在指针中使用 ++ 操作数,我的值就会出错
- 二进制表达式的操作数无效 - 使用 for 和迭代器
- C2679 二进制"<<":未找到采用右操作数类型的运算符
- CPP 运算符重载操作数位置 [] 与 ==