C++中的继承和模板:为什么以下一段代码不编译?

Inheritance and template in C++: Why doesn't the following piece of code compile?

本文关键字:一段 代码 编译 继承 为什么 C++      更新时间:2023-10-16

我有一个简单的c ++程序,我无法编译,虽然我试图在谷歌中搜索并尝试阅读模板,继承和向量,但我没有任何线索,我犯了什么错误,任何人都可以帮助我!!以下是代码:

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++ 示例.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 来访问模板基类中的成员变量foo。你可能会问为什么。

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

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;
}

现场演示在这里

您的主方法有语法错误,请更改为:

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

你可以把其他类型而不是整数...

在 C++ 中,模板是编译时