Overload function on parent and child - how to access the parent function
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;
}开发者_StackOverflow社区
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.
Try ss<<(Msg const&)in
.
And probably you have to make operator a friend of Greeting
class.
#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;
}
Not great design, but solves your problem.
精彩评论