C++ 无法返回继承的类对象



我在多态性方面遇到了麻烦,事情是这样的。我使用的是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;
}

该方法不完整,并且在返回行中有一个fail。

我尝试进行强制转换,但当我使用typeid().name()时,我有InternalMsg,但没有继承的类名。

非常感谢。

您使用的是私有继承,因为class的默认值是private:

class Event: InternalMsg {

这意味着Event不是InternalMsg,并且无法进行从Event*InternalMsg*的转换。

您应该使用公共继承:

class Event: public InternalMsg {

或者,因为您的所有成员都是公共的,所以使用struct的默认值是public:这一事实

struct Event: InternalMsg {

最新更新