c++ - C++中的模板参数继承

标签 c++ templates inheritance polymorphism

好久没写C++了,有点生疏了。如果我有这样的类(class):

class JsonType{
    protected:
        map<string, JsonType>* objects;
}

和一个继承自它的类:

class JsonObject : public JsonType{
    public:
        JsonObject(){
            this->objects = new map<string, JsonObject>();
        }
}

为什么我会收到编译器错误 cannot convert...JsonObject...to...JsonType?这不应该是合法的,因为 JsonObject 是一个 JsonType 吗?

最佳答案

您可以将 JsonObject 对象添加到映射中,但类型不匹配无法初始化。

编辑:您必须将其初始化为:

this->objects = new map<string, JsonType>();

但是如果你有任何一个对象:

JsonType js = new JsonType();

JsonObject js2 = new JsonObject();

JsonType js3 = new JsonObject();

您可以将这些对象中的任何一个添加到如上初始化的 map 中。

关于c++ - C++中的模板参数继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11641804/

相关文章:

c++ - 通过 UDP 发送 XML 数据

c++ - 在opencv中对有界矩形进行排序

c++ - 线性链式工厂和 move 语义

linux - 使用继承时覆盖 Puppet 类

inheritance - 在 GitLab CI 中使用 `extends` 时,哪些作业属性会被合并或覆盖?

c++ - 这个运算符重载代码有什么问题?

c++ - 如何使用 "wrapper function"调用不带参数的递归函数 n 次?

C++ 从函数签名中提取参数

c++ - 带有切换实例化模板的枚举的工厂

c++ - 从对象 vector 中获取成员 vector