【问题标题】:how to fix this (fundation templates &inheritance)如何解决这个问题(基础模板与继承)
【发布时间】:2020-06-06 03:35:48
【问题描述】:

refrence:enter image description here/

[C++ 错误] homeworkUnit1.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&lt;T&gt;
  • .@songyuanyao 你能告诉我更多细节,我需要改变的地方不好对不起,我是初学者
  • template&lt;class T&gt;stack&lt;T&gt;::stack(int num):bag&lt;T&gt;( num){
  • 谢谢我修好了!! :]

标签: c++ templates inheritance


【解决方案1】:

由于你继承bag&lt;T&gt;,你必须指定bag&lt;T&gt;作为你想要显式构造的继承类型:

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 实际上并不是一个类型——它是一个类型模板。

【讨论】:

  • 哦,我明白了。非常感谢。 : >
猜你喜欢
  • 2015-04-20
  • 2014-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 2011-09-14
  • 2013-01-24
相关资源
最近更新 更多