重载父和子函数-如何访问父函数
Overload function on parent and child - how to access the parent function
我想这样做:
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;
}
不是很好的设计,但是可以解决你的问题。
相关文章:
- 如何在函数外部访问函数中局部变量的值?
- UChildActorComponent的ChildActorClass中的访问函数
- 访问函数变体时"Invalid conversion"错误
- 在将向量作为参数传递给函数后,我无法访问函数中向量的元素
- 在64位DLL中访问函数的错误
- 访问函数中 const char *arr[] 的元素
- 访问函数的调用方类型
- 访问函数中的使用声明:与范围相关的问题
- 通过 -> 语法 c++ 从指针访问函数
- 在函数中使用 const 引用参数访问函数中成员的最佳实践 C++.
- 从另一个文件(C++,QT)访问函数未解析的外部
- 如何从主(C )访问函数中的值
- 访问函数 c++ 中的全局变量
- C++ GoogleTest 使用夹具 - 无法访问函数指针定义
- 在不知道名称的情况下访问函数参数
- C++:直接访问器或类内的访问函数
- 无法从对象访问函数
- 类的2D矢量在访问函数时出错
- 为什么在C++中访问函数时没有对象
- 我无法使用指针数组从main访问函数(在类中)