重载父和子函数-如何访问父函数

Overload function on parent and child - how to access the parent function

本文关键字:访问 函数 子函数 重载 何访问      更新时间:2023-10-16

我想这样做:

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失败,因为Msg是抽象的。然而,我想有代码输出的信息为父母在只有一个地方。正确的做法是什么?谢谢!

编辑:对不起,只是为了清楚,这是这一行return ss << (Msg)in << " Text " << in.text;我不知道如何写

试试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;
}

不是很好的设计,但是可以解决你的问题。