5

简单类.h

class SimpleClass
{
    int i;

    public:
    SimpleClass() : i(0) {}
    SimpleClass(int j) : i(j) {}
    friend std::ostream& operator<<(std::ostream&, const SimpleClass&);
};

简单类.cpp

#include <ostream>
#include "SimpleClass.h"

std::ostream& operator<<(std::ostream& out, const SimpleClass& obj)
{
    out << "SimpleClass : " << obj.i << '\n';
    return out;
}

基类和派生类.h

class BaseClass
{
    protected:
    int i;

    public:
    BaseClass() : i(0) {}
    BaseClass(int j) : i(j) {}
    virtual void print(std::ostream& out) const { out << "BaseClass : " << i << '\n'; }
};

class DerivedClass : public BaseClass
{
    int j;

    public:
    DerivedClass() : BaseClass(), j(0) {}
    DerivedClass(int m, int n) : BaseClass(m), j(n) {}
    void print(std::ostream& out) { out << "DerivedClass : " << i << ' ' << j << '\n'; }
};

std::ostream& operator<<(std::ostream&, const BaseClass&);

基类和派生类.cpp

#include <ostream>
#include "Base and Derived Classes.h"

std::ostream& operator<<(std::ostream& out, const BaseClass& obj)
{
    obj.print(out);
    return out;
}

主文件

#include <iostream>
#include "SimpleClass.h"
#include "Base and Derived Classes.h"

int main()
{
    SimpleClass simple(10);
    std::cout << simple;
    BaseClass base(100);
    std::cout << base;
    DerivedClass derived(100, 200);
    std::cout << derived;                   //  Doesn't call derived.print(), but base.print() instead. Why ?
}
4

3 回答 3

20
virtual void print(std::ostream& out) const 

未被覆盖

void print(std::ostream& out)

(因为const)。

于 2013-01-17T19:09:17.600 回答
8

您忘记了派生类中const的定义。print

于 2013-01-17T19:09:18.333 回答
5

在你DerivedClassprint()方法必须是const,就像它在BaseClass

void print(std::ostream& out) const
于 2013-01-17T19:09:23.713 回答