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;
我不知道该怎么写。
它违反了常量的正确性。 –
代替'(Msg)in',写入'static_cast(in)'。 –
“in.text”?你正在访问私人会员使用虚线符号..这将反过来给编译错误。访问私人成员只能通过getters和setters函数 – Arunmu