打印操作员超载失败?

我在练习C ++基本继承概念时,遇到了打印出一个自定义类对象并写入一个过载的需求,完全按照指导原则进行,但仍未注册使用新操作符进行打印(<<)。

我想知道是否输入错误或在其他地方有一些声明/启动错误?

'operator <<'没有匹配(操作数类型是'std :: basic_ostream'和'Choco')std :: cout <<“Choco value:”<< child << 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!
}

因为它不是类成员,所以在类之外定义了以下方式。

std::ostream & operator <<( std::ostream &os, const Choco &c ) 
{
    return os << c.full;
}

考虑到该功能

bool eat() {
    full = true;
}

应该有一个带有bool类型表达式的return语句,或者应该在基类和派生类中用返回类型void声明它。

链接地址: http://www.djcxy.com/p/73153.html

上一篇: Print Operator overload fail?

下一篇: C++ template class and operator overloading