流<<运算符没有被调用
我创建了一个具有一些基本属性的 Animal 类,并添加了一个无数据构造函数。 我还重载了 ostream 运算符来打印属性。
Animal.cpp
#include<bits/stdc++.h>
using namespace std;
class Animal {
string name;
int action;
public:
Animal() {
name = "dog";
action = 1;
}
ostream& write(ostream& os) {
os << name << "\n" << action << "\n";
return os;
}
friend ostream& operator<<(ostream& os, Animal &animal) {
return animal.write(os);
}
};
int main() {
cout << "Animal: " << Animal() << "\n";
}
但是,我在主要错误中发现二进制表达式 ostream 和 Animal 的操作数无效。 如果我声明 Animal 然后调用 cout,效果很好。但是如何让它像这样工作(同时初始化和cout)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
operator<<
的第二个参数声明为Animal &
;Animal()
是临时的,不能绑定到非常量的左值引用。您可以将类型更改为
const Animal &
;临时可以绑定到 const 的左值引用。 (然后write
也需要标记为const
。)The 2nd parameter of
operator<<
is declared asAnimal &
;Animal()
is a temporary and can't be bound to lvalue-reference to non-const.You can change the type to
const Animal &
; temporary could be bound to lvalue-reference to const. (Thenwrite
needs to marked asconst
too.)