2011-08-13 61 views
0

這是我希望做什麼:過載功能 - 如何訪問父功能

class Msg { 
    int target; 
public: 
    Msg(int target): target(target) { } 
    virtual ~Msg() { } 
    virtual MsgType GetType()=0; 
}; 

inline std::ostream& operator <<(std::ostream& ss,Msg const& in) { 
    return ss << "Target " << in.target; 
} 

class Greeting : public Msg { 
    std::string text; 
public: 
    Greeting(int target,std::string const& text) : Msg(target),text(text); 
    MsgType GetType() { return TypeGreeting; } 
}; 

inline std::ostream& operator <<(std::ostream& ss,Greeting const& in) { 
    return ss << (Msg)in << " Text " << in.text; 
} 

不幸的是,這並不能作爲投味精在倒數第二行的工作失敗因爲Msg是抽象的。然而,我想讓代碼只在一個地方輸出父代的信息。什麼是正確的方法來做到這一點?謝謝!

編輯:對不起,只是要清楚,這是這一行return ss << (Msg)in << " Text " << in.text;我不知道該怎麼寫。

+0

它違反了常量的正確性。 –

+0

代替'(Msg)in',寫入'static_cast (in)'。 –

+0

「in.text」?你正在訪問私人會員使用虛線符號..這將反過來給編譯錯誤。訪問私人成員只能通過getters和setters函數 – Arunmu

回答

1

嘗試ss<<(Msg const&)in。 而且可能你必須讓操作員成爲Greeting類的朋友。

#include "iostream" 
#include "string" 

typedef enum { TypeGreeting} MsgType; 

class Msg { 
    friend inline std::ostream& operator <<(std::ostream& ss,Msg const& in); 

    int target; 
public: 
    Msg(int target): target(target) { } 
    virtual ~Msg() { }; 
     virtual MsgType GetType()=0; 
}; 

inline std::ostream& operator <<(std::ostream& ss,Msg const& in) { 
    return ss << "Target " << in.target; 
} 

class Greeting : public Msg { 
    friend inline std::ostream& operator <<(std::ostream& ss,Greeting const& in); 

    std::string text; 
public: 
    Greeting(int target,std::string const& text) : Msg(target),text(text) {}; 
    MsgType GetType() { return TypeGreeting; } 

}; 

inline std::ostream& operator <<(std::ostream& ss,Greeting const& in) { 
    return ss << (Msg const&)in << " Text " << in.text; 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    Greeting grt(1,"HELLZ"); 
    std::cout << grt << std::endl; 
    return 0; 
} 

不是偉大的設計,但解決您的問題。