2015-05-16 45 views
1

對象的基類的指針數組我有以下問題。指向包含派生類和重載<<運算符

我已經創建了一個指向基類對象的指針數組,但我在這個數組中存儲了指向派生類中的對象的指針。

我還重載了每個類中的<<operator以顯示對象。 但是,當我將這個重載的<<operator應用於上述數組時,它將所有指針視爲指向基類的對象。

下面我介紹描述問題的代碼。 我需要這個重載操作符才能正常工作,因爲我需要將數組指向的對象保存在文件中。

#include <iostream> 
    #include <cstdio> 
    #include <cstdlib> 

    using namespace std; 

    class Base 
    { 
     public: 
     int basevar; 
     Base(): basevar(1) {}; 
     virtual void dosth(){}; 
     friend ostream & operator<<(ostream & screen, const Base & obj); 
    }; 

    ostream & operator<<(ostream & screen, const Base & obj) 
    { 
     screen << obj.basevar; 
     return screen; 
    }; 

    class Der1: public Base 
    { 
     public: 
     int de1; 
     Der1(): de1(2) {}; 
     virtual void dosth() 
     { 
      cout << "Der1" << endl; 
     } 
     friend ostream & operator<<(ostream & screen, const Der1 & obj); 
    }; 

    ostream & operator<<(ostream & screen, const Der1 & obj) 
    { 
     Base b; 
     b = static_cast <Base>(obj); 
     screen << b; 
     screen << " " << obj.de1; 
     return screen; 
    }; 

    class Der2: public Base 
    { 
     public: 
     int de2; 
     Der2(): de2(3) {}; 
     virtual void dosth() 
     { 
      cout << "Der2" << endl; 
     } 
     friend ostream & operator<<(ostream & screen, const Der2 & obj); 
    }; 

    ostream & operator<<(ostream & screen, const Der2 & obj) 
    { 
     Base b; 
     b = static_cast <Base>(obj); 
     screen << b; 
     screen << " " << obj.de2; 
     return screen; 
    } 

    int main() 
    { 
     Base * array[] = {new Base(), new Der1(), new Der2()}; 
     for(int i=0; i<3; ++i) 
     { 
      cout << *array[i]; // <- always displays objects as if they were from the base class 
     } 
     return 0; 
    } 
+0

[Making operator << virtual?]的可能重複(http://stackoverflow.com/questions/4571611/making-operator-virtual) – Petr

回答

3

你可以在基類中聲明一個虛函數如下方式

class Base 
{ 
    public: 
    int basevar; 
    Base(): basevar(1) {}; 
    virtual std::ostream & out(std::ostream &os) const 
    { 
     return os << basevar; 
    } 

    virtual void dosth(){}; 
    friend ostream & operator<<(ostream & screen, const Base & obj); 
}; 

在這種情況下,運營商將像

ostream & operator<<(ostream & screen, const Base & obj) 
{ 
    return obj.out(screen); 
}; 

,並在派生類中重新定義虛函數。例如

class Der1: public Base 
{ 
    public: 
    int de1; 
    Der1(): de1(2) {}; 
    std::ostream & out(std::ostream &os) const 
    { 
     return Base::out(os) << " " << obj.de1; 
    } 
    virtual void dosth() 
    { 
     cout << "Der1" << endl; 
    } 
}; 

在這種情況下,不需要爲派生類定義運算符。