[英]Overloading output stream for my own class
I have a base class Animal that class Cat and Dog derive from. 我有一个基类,动物是猫和狗的起源。
I'm trying to overload the output stream so I can do something like this: 我正在尝试使输出流超载,以便可以执行以下操作:
Animal *a = (animal *) 0;
while(read_animal(cin, a) && a) // a has been assigned a derived class
cout << *a << '\n';
And here's how I've overloaded it: 这就是我如何重载它:
ostream& operator<<(ostream &a, const animal* animal) {
return a << animal->describe() << endl;
}
But I get an error: 但是我得到一个错误:
Error 20 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'animal' (or there is no acceptable conversion) 错误20错误C2679:二进制'<<':未找到采用'动物'类型的右侧操作数的运算符(或者没有可接受的转换)
Ideas? 有想法吗?
Your overload expects const animal*
but what you are supplying is *a
ie animal
, not animal*
. 您的重载需要const animal*
但是您提供的是*a
即animal
,而不是animal*
。 So you may try: 因此,您可以尝试:
cout << a << '\n';
Try 尝试
cout << a << '\n';
Since your overload expects a const animal* animal
由于您的超负荷期望使用const animal* animal
Alternatively change the signature of your function to: 或者,将函数的签名更改为:
ostream& operator<<(ostream &a, const Animal& animal) {
return a << animal.describe() << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.