Print Operator overload fail?

Am practicing C++ basic inheritance concepts, came across the need to print out a custom class object and wrote an overload, followed guide exactly yet still does not register use of the new operator for printing (<<).

Am wondering if typed incorrectly or had some declaration/initiation errors somewhere else?

no match for 'operator<<' (operand types are 'std::basic_ostream' and '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!
}

The operator is defined the following way outside the class because it is not a class member.

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

Take into account that the function

bool eat() {
    full = true;
}

shall have a return statement with an expression of the type bool or it should be declared with the return type void in the base and derived classes.

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

上一篇: C ++

下一篇: 打印操作员超载失败?