c++ 不能 return 继承的 class 对象
c++ can't return a inherited class object
我在多态性方面遇到了麻烦,这就是问题所在。我正在使用 rapidjson,在我得到 JSON 字符串并将其转换后,我需要一种方法来发送 SUPERCLASS InternalMsg 的对象,但我需要发送继承的 class 对象。
例子
class InternalMsg{
public:
virtual ~InternalMsg() {};
};
class Event: InternalMsg{
public:
Event(){};
char* type;
char* info;
};
class ScanResult : public InternalMsg{
public:
int id_region;
int result;
};
这是 classes,这是方法,就像我说的,我正在使用 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;
}
该方法不完整,return行失败。
我尝试进行转换,但是当我使用 typeid().name() 时,我有 InternalMsg 但没有继承的 class 名称。
非常感谢。
您正在使用私有继承,因为 class
的默认值是 private
:
class Event: InternalMsg {
这意味着 Event
不是 InternalMsg
,并且从 Event*
到 InternalMsg*
的转换不能采取地点。
你应该使用 public 继承:
class Event: public InternalMsg {
或者,由于您的所有成员都是 public,因此使用 struct
的默认值是 public
:
struct Event: InternalMsg {
我在多态性方面遇到了麻烦,这就是问题所在。我正在使用 rapidjson,在我得到 JSON 字符串并将其转换后,我需要一种方法来发送 SUPERCLASS InternalMsg 的对象,但我需要发送继承的 class 对象。
例子
class InternalMsg{
public:
virtual ~InternalMsg() {};
};
class Event: InternalMsg{
public:
Event(){};
char* type;
char* info;
};
class ScanResult : public InternalMsg{
public:
int id_region;
int result;
};
这是 classes,这是方法,就像我说的,我正在使用 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;
}
该方法不完整,return行失败。
我尝试进行转换,但是当我使用 typeid().name() 时,我有 InternalMsg 但没有继承的 class 名称。
非常感谢。
您正在使用私有继承,因为 class
的默认值是 private
:
class Event: InternalMsg {
这意味着 Event
不是 InternalMsg
,并且从 Event*
到 InternalMsg*
的转换不能采取地点。
你应该使用 public 继承:
class Event: public InternalMsg {
或者,由于您的所有成员都是 public,因此使用 struct
的默认值是 public
:
struct Event: InternalMsg {