[英]C++ Combining Class Inheritance and Templates
I have an assignment that involves inheritance and templates.我有一个涉及继承和模板的作业。 I'm supposed to create a music player program and create several classes that inherit the functions of the linked list.我应该创建一个音乐播放器程序并创建几个继承链表功能的类。
What I'm getting thrown off on, is inheriting a class template, to a class that is required to not have a template .我被抛弃的是继承一个类模板到一个不需要模板的类。
This is what I have so far.这是我到目前为止。 This is the class that is being inherited:这是正在继承的类:
#ifndef LINKED_LIST_
#define LINKED_LIST_
#include <memory>
#include "ListInterface.h"
#include "Node.h"
template <typename ItemType>
class LinkedList : public ListInterface<ItemType> {
// ...
This is the class that's going to take the functions from the base class:这是将从基类中获取函数的类:
#ifndef DISC_
#define DISC_
#include <memory>
#include "LinkedList.h"
class Disc : public LinkedList {
// ...
I understand that I need to pass the template through the LinkedList declaration for the second block of code.我知道我需要通过 LinkedList 声明为第二个代码块传递模板。 However, I'm unsure how to do this.但是,我不确定如何执行此操作。 Something that I tried was:我尝试过的东西是:
template <typename ItemType>
class Disc : public LinkedList<ItemType> {
// ...
But would this declare the Disc class as a template?但这会将 Disc 类声明为模板吗? That's what my instructor told me.这是我的导师告诉我的。 Thanks.谢谢。
But would this declare the Disc class as a template?但这会将 Disc 类声明为模板吗?
Yes.是的。 If you want to have a type (not a template) that you can inherit from, you need to instantiate LinkedList
.如果您想拥有可以继承的类型(而不是模板),则需要实例化LinkedList
。 You can for example have a LinkedList
of Disc
s that would be LinkedList<Disc>
.例如,您可以拥有一个Disc
的LinkedList
,即LinkedList<Disc>
。 And Disc
can be declared as并且Disc
可以声明为
class Disc : public LinkedList<Disc> {};
Note that LinkedList<Disc>
is not a template.请注意, LinkedList<Disc>
不是模板。 It is a type like others, hence also Disc
does not have to be a template.它与其他类型一样,因此Disc
也不必是模板。 I had to do some guessing to choose the template parameter.我不得不做一些猜测来选择模板参数。 I don't think Disc
inheriting from a LinkedList<Disc>
is a sound design.我不认为Disc
从继承LinkedList<Disc>
是一个完善的设计。 However, this is another possibility that would not be less odd:然而,这是另一种不那么奇怪的可能性:
class Disc : public LinkedList<int> {};
The point here is just to realize that LinkedList<int>
is not a template, just like eg std::vector<int>
is not a template.这里的重点只是要意识到LinkedList<int>
不是模板,就像std::vector<int>
不是模板一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.