父函数和子函数的重载 - 如何访问父函数
这是我想做的:
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 << (消息)在<< 《正文》<< in.text;
我不知道怎么写。
Here is what I would like to do:
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;
}
Unfortunately, this doesn't work as the cast to Msg on the second last line fails as Msg is abstract. I would however like to have the code to output the information for the parent in only one place. What is the correct way to do this? Thanks!
EDIT: Sorry, just to be clear, it is this line return ss << (Msg)in << " Text " << in.text;
I don't know how to write.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试
ss<<(Msg const&)in
。也许你必须让操作员成为
Greeting
类的友元。不是很好的设计,但解决了你的问题。
Try
ss<<(Msg const&)in
.And probably you have to make operator a friend of
Greeting
class.Not great design, but solves your problem.