简体   繁体   English

C ++继承和模板

[英]C++ inheritance and templates

I have a List template. 我有一个列表模板。

I want to make a list of Jobs. 我想列出一份工作。 However, I have different jobs when the only different thing is the function executeJob(). 但是,当唯一不同的是函数executeJob()时,我会有不同的工作。

So I have a class Job: 所以我有一个班级的工作:

class Job{...
...
public:
..
virtual SomeType executeJob() = 0;
}

So it's actually an abstract class and in the derived classes all the private fields are the same and it has the implementation for its own executeJob(). 因此,它实际上是一个抽象类,在派生类中,所有私有字段都相同,并且具有自己的executeJob()实现。

Lets say there are 2 different type of derived classes called Job1 and Job2 so I actually want my list to be able to have Job1 objects and job2 Objects as well. 可以说有两种不同类型的派生类,分别称为Job1Job2因此我实际上希望我的列表也能够具有Job1 objectsjob2 Objects

My list is defined this way: List<Job> . 我的列表是这样定义的: List<Job>

But in the ListNode c'tor I have this: 但是在ListNode中,我有这个:

    listNode(const T& value) : value(new T(value)), prevNode(NULL),
    nextNode(NULL){}

and of course I have a problem with the line: value(new T(value)) as it's an abstract class. 当然,我对以下行有问题: value(new T(value))因为它是抽象类。 How do I solve it so I still can hold a list of both Job1 and Job2 objects and define it as List<Job> ? 我该如何解决,以便仍可以同时保存Job1 and Job2 objects List<Job>并将其定义为List<Job>

Simple, you can't take T in the constructor. 很简单,您不能在构造函数中使用T

You need a templated constructor, that takes the real class. 您需要一个带模板的构造函数,该构造函数采用真实的类。 Then you will call the constructor on the type of the parameter. 然后,您将根据参数的类型调用构造函数。

If you don't have the type, and only pass around "Job", then you will have to switch to prototype based design with a virtual clone() method (instead of calling the constructor). 如果没有类型,而只传递“ Job”,则必须使用虚拟clone()方法(而不是调用构造函数)切换到基于原型的设计。

Edit: Since you are using new , I'm assuming that the List<Job> is a typo and you meant List<Job*> 编辑:由于您使用的是new ,所以我假设List<Job>是一个错字,而您的意思是List<Job*>

You cannot have a list containing different objects. 您不能有包含不同对象的列表。

You could have a list of pointers to base class though. 但是,您可能有一个指向基类的指针列表。

The thing that the other answers are not covering well is that when you have a templated class C and you instantiate that class with two different template types, for all practical purposes the compiler sees these as being two distinct classes, not one class instantiated in two ways. 其他答案不能很好地解决的问题是,当您拥有模板化的类C并使用两种不同的模板类型实例化该类时,出于所有实际目的,编译器将其视为两个不同的类,而不是将一个实例化为两个类方法。

The types are incompatible unless you take the suggestion provided of storing pointers to a base class in your list. 这些类型是不兼容的,除非您接受建议在列表中存储指向基类的指针。 This way, if B and D derive off of A, then you can store B*'s and D*'s in the list, but access them through an A*. 这样,如果B和D派生自A,则可以将B *和D *存储在列表中,但可以通过A *访问它们。

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

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