c++ - C++ 中的继承和模板 : Why doesn't the following piece of code compile?

标签 c++ templates c++11 inheritance g++

我有一个简单的 C++ 程序,我无法编译它,尽管我尝试在 google 中搜索并尝试阅读有关模板、继承和 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++ 示例.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.

此外,正如老狐狸所解释的那样,在声明变量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;
}

live demo here

关于c++ - C++ 中的继承和模板 : Why doesn't the following piece of code compile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29876488/

相关文章:

c++ - 在 C++ 中从 Linux 应用程序发送电子邮件

没有初始化就使用 C++ 变量?

c++ - 无法通过引用 std::exception 捕获从 std::exception 派生的类

c++ - 这个类的行为与其父类相同吗?

c++11 - 可变模板函数的显式实例化

multithreading - c++ 11线程未知输出

c++ - 我应该返回 bool 还是 const bool?

c++ - 固定大小和零初始化数组作为 C++11 中的默认参数

templates - 如果标签名称中包含 ".",我如何获取 Docker 镜像的标签?

c++ - 在容器中存储模板化对象