如何解决此问题(基础模板和继承)

how to fix this (fundation templates &inheritance)

本文关键字:继承 何解决 解决 问题      更新时间:2023-10-16

引用:enter image description here/

[C++错误] 家庭作业单元1.cpp(39(: E2102 如果不指定
专用化参数,则无法使用模板"bag"
积分代码: https://drive.google.com/file/d/1wBe7IqHngArjK3WVSN3u-mboKhrMkIao/view?usp=sharing
(使用 Borland C++ Builder(

.h

template <class T>
class bag{
public:
bag(int);//
~bag();
String result();
T *data;
bool empty,full; 
protected:
int size,position;
String ans;  
};
template <class T>
class stack:public bag<T>{
public:
stack(int);
void push(int);
void pop();
};
template <class T>
class queue:public bag<T>{
public:
queue(int);
void enq(int);
void deq();
};

。.cpp

stack<float> *s;
queue<float> *q;
template<class T>bag<T>::bag(int num){
empty,full=false;
size=num;
data=new T [size];
position=0;
}
template<class T>bag<T>::~bag(){
delete []data;
}
template<class T>String bag<T>::result(){
String ans="";
for(int i=0;i<=position-1;i++){
ans+= AnsiString(data[i]);
}
return ans;
}
**template<class T>stack<T>::stack(int num):bag( num){//how to fix this
}**

我需要添加什么或我的代码有误

由于您继承了bag<T>,因此您必须将bag<T>指定为要显式构造的继承类型:

template<class T> stack<T>::stack(int num) : bag<T>(num) {
//                Specify the template argument ^^^

这是必需的,因为C++允许多重继承,并且您可以继承同一模板的不同实例:

template <typename> class foo {};
class bar : public foo<int>, public foo<float> {
public:
bar();
};
bar::bar() : foo{} {}
//           ^^^
// Same problem, but now it's clear why: which foo instantiation?
// foo<int> or foo<float>?

而且,也许同样重要的是,当你显式调用基类型构造函数时,语法说你必须指定一个类型,而bag实际上不是一个类型 - 它是一个类型模板。