我在多态性方面遇到了麻烦,这就是问题所在。我正在使用 rapidjson,在我获得 JSON 字符串并将其转换后,我需要一种方法来发送 SUPERCLASS InternalMsg 的对象,但我需要发送继承的类对象。
例子
class InternalMsg{
public:
virtual ~InternalMsg() {};
};
class Event: InternalMsg{
public:
Event(){};
char* type;
char* info;
};
class ScanResult : public InternalMsg{
public:
int id_region;
int result;
};
这是类,这是方法,就像我说的,我正在使用 rapidjson:
InternalMsg* JsonPackage::toObject(){
Document doc;
doc.Parse<0>(this->jsonString);
if(doc["class"] == "Event"){
Event* result = new Event;
result->type= (char*)doc["type"].GetString();
result->info = (char*)doc["info"].GetString();
return result;
}else{
std::cout << "No object found" << "\n";
}
return NULL;
}
方法不完整,返回行失败。
我尝试进行转换,但是当我使用 typeid().name() 时,我有 InternalMsg 但没有继承的类名。
非常感谢。
最佳答案
您正在使用私有(private)继承,因为 class
的默认值是 private
:
class Event: InternalMsg {
这意味着 Event
is-not-an InternalMsg
,以及从 Event*
到 的转换>InternalMsg*
无法发生。
你应该使用公共(public)继承:
class Event: public InternalMsg {
或者,由于您的所有成员无论如何都是公开的,因此使用 struct
的默认值是 public
的事实:
struct Event: InternalMsg {
关于C++ 无法返回继承的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29234041/