2011-08-13 35 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; 
} 

不是伟大的设计,但解决您的问题。