2013-01-17 16 views
5

SimpleClass.hDlaczego polimorfizm nie działa w tym przypadku?

class SimpleClass 
{ 
    int i; 

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

SimpleClass.cpp

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

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

bazowa i pochodnych Classes.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&); 

bazowa i pochodnych Classes.cpp

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

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

main.cpp

#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 ? 
} 
+0

Co (konkretnie) nie działa? Czego oczekujesz i jak to się różni od wyniku? – iamnotmaynard

+0

Funkcja print() jest const w klasie bazowej, ale nie jest const w klasie pochodnej. Podpis musi być taki sam. – tp1

+0

@ tp1 Zgadza się. Przyjmuję twoją odpowiedź. Dzięki. – Belloc

Odpowiedz

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

nie jest zastępowana przez

void print(std::ostream& out) 

(gdyż const).

+4

+1. 'const' -ness funkcji member jest ** częścią ** podpisu! – Nawaz

8

Zapomniałeś const o definicji print w klasie pochodnej.

5

W swojej DerivedClass metody print() musi być const, jak to jest w BaseClass:

void print(std::ostream& out) const 
Powiązane problemy