在练习C ++基本继承概念时,遇到了打印自定义类对象并写入重载的需要,紧接着指南仍然没有注册使用新运算符进行打印(<<<)。
我想知道输入不正确或在其他地方有一些声明/启动错误吗?
不匹配'operator<<'(操作数类型是 'std :: basic_ostream'和'Choco')std :: cout<< "巧克力价值:" <<孩子<< ENDL;
#include <iostream>
using namespace std;
class Sweets {
public:
// pure virtual, child MUST implement or become abstract
// Enclosing class becomes automatically abstract - CANNOT instantiate
virtual bool eat() = 0;
};
// public inheritance : public -> public, protected -> protected, private only accessible thru pub/pro members
class Choco : public Sweets {
public:
bool full;
Choco() {
full = false;
}
// Must implement ALL inherited pure virtual
bool eat() {
full = true;
}
// Overload print operator
bool operator<<(const Choco& c) {
return this->full;
}
};
int main() {
// Base class object
//sweets parent;
Choco child;
// Base class Ptr
// Ptr value = address of another variable
Sweets* ptr; // pointer to sweets
ptr = &child;
std::cout<< "Sweets* value: " << ptr << endl;
std::cout<< "Choco address: " << &child << endl;
std::cout<< "Choco value: " << child << endl; // Printing causes error!
}
答案 0 :(得分:0)
运算符在类外定义如下,因为它不是类成员。
std::ostream & operator <<( std::ostream &os, const Choco &c )
{
return os << c.full;
}
考虑到功能
bool eat() {
full = true;
}
应该有一个带有bool
类型表达式的return语句,或者它应该在基类和派生类中使用返回类型void
声明。