我有一个简单的c++程序,尽管我试图在google中搜索并尝试阅读有关template,继承和vector的信息,但我却无法编译,但是我不知道我在做什么错误,任何人都可以。请帮我!!
以下是代码:

template <class T>
class Base
{
  public:
  int entries;
};
template <class T>
class Derive : public Base<T *>
{
  public:
  int j;
  void pankaj(){j = entries;}
  void clear();

};
template <class T> void Derive<T>::clear()
{
  int i;
  int j=entries;
};
int main()
{
  Derive b1;
}

而且我得到以下错误:
pankajkk> g++ sample.cpp
sample.cpp: In member function 'void Derive<T>::pankaj()':
sample.cpp:14: error: 'entries' was not declared in this scope
sample.cpp: In member function 'void Derive<T>::clear()':
sample.cpp:22: error: 'entries' was not declared in this scope
sample.cpp: In function 'int main()':
sample.cpp:26: error: missing template arguments before 'b1'
sample.cpp:26: error: expected `;' before 'b1'

谢谢!!

最佳答案

您必须使用this->foo来访问模板基类中的成员变量fooYou may ask why.

另外,正如Old Fox解释的那样,在声明变量T时必须指定b1类型。

template <class T>
class Base
{
  public:
  int entries;
};

template <class T>
class Derive : public Base<T *>
{
  public:
  int j;
  void pankaj(){j = this->entries;}
  void clear();
};

template <class T> void Derive<T>::clear()
{
  int i;
  int j=this->entries;
};

int main()
{
  Derive<int> b1;
}

live demo here

关于c++ - C++中的继承和模板:为什么以下代码无法编译?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29876488/

10-11 22:43
查看更多