简体   繁体   English

C ++中的列表继承

[英]List inheritance in C++

I'm doing a program that involve a lot of lists of multiple class. 我正在做一个涉及很多多个类列表的程序。 I'm pretty sure it has a name but I don't really know how to call it, what I would like to do is to make a common list which contain some functions (like element insertion, getter...) which all lists inherit and can use functions of the common list. 我很确定它有一个名字,但是我真的不知道怎么称呼它,我要做的是制作一个包含一些函数(例如元素插入,getter ...)的通用列表,所有这些列表继承并可以使用公用列表的功能。 So my question is how to do it with an example if possible. 所以我的问题是,如果可能的话,如何举一个例子。 I've made a header code example below. 我在下面做了一个标题代码示例。

class CommonList {
  public:
        // Add some functions
        // T here is not a class I've made.
        void insere(T element);
        T getElement(int id);
  protected:
        std::map<int,T> m_map;
};

class A {
    public: A();
}

class B {
    public: B();
}

class ListA : public CommonList {
    // Tell the program that element T are ONLY object of class A.
    // Like if I would have made this.
    /*
  public:
        void insere(A element);
        A getElement(int id);
  protected:
        std::map<int,A> m_map;
    */
};

class ListB : public CommonList {
    // Same for B.
}

I'm pretty sure it has a name but I don't really know how to call it 我很确定它有一个名字,但是我真的不知道怎么称呼它

The word you are looking for is a template class. 您要查找的单词是模板类。

And this is how it is being done: 这是它的完成方式:

template <typename T>
class CommonList {
public:
    void insert(T element){
        /* Implement your insert function here */
    };
    T getElement(int id){
        /* Implement your getElement function here */
    };
protected:
    std::map<int,T> m_map;
};

And then you can simply create any type of that list, for example: 然后,您可以简单地创建该列表的任何类型,例如:

int main(){
    CommonList<int> int_list;
    my_list.insert(7);
    CommonList<double> double_list;
    my_list.insert(4.3);
}

You may of course also inherit from this class to and override the functions as you wish. 当然,您也可以从该类继承并根据需要覆盖函数。

class A{}; 
class ListA : public CommonList<A>{
    // ... 
};

Or as a template 或作为模板

template <typename T>
class ListT : public CommonList<T>{
    // ...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM