gpt4 book ai didi

c++ - 父子函数重载 - 如何访问父函数

转载 作者:行者123 更新时间:2023-11-28 08:17:50 25 4
gpt4 key购买 nike

这是我想做的:

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 .可能你必须让 operator 成为 Greeting 的 friend 类。

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

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

关于c++ - 父子函数重载 - 如何访问父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7051741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com