如何继承带有模板的类? [英] how to inherit a class with templates?

查看:55
本文介绍了如何继承带有模板的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下各项可以正常工作:

Why would the following work just fine:

class a
{
   public:
    int n;
};

class b : public a
{
 public:
  b()
  {
      n = 1;
  }
};

int main()
{
}

但这不起作用:

template <class T>
class a
{
   public:
      int n;
};

template <class T>
class b : public a<T>
{
   public:
    b()
    {
       n = 1;
    }
};

int main()
{
}

并显示以下错误:

 1.cpp: In constructor ‘b<T>::b()’:
 1.cpp:14: error: ‘n’ was not declared in this scope

又如何在继承模板类的同时使用其基本成员并保持类型通用呢?

and how would one inherit a template class while being able to use its base members and keep the type generic?

推荐答案

您需要使用" this "或" using "指令(或明确使用具有基层资格的人.

You need to qualify it with "this" or with a "using" directive (or explicitly with the base class qualification).

简而言之:该变量是非依赖类型(不依赖于模板类的T ),

In a nutshell: that variable is a nondependent type (non-dependent on the T of the template class), the compiler doesn't look into a dependent type (your a< T >) when looking for declarations for a nondependent type.

this-> n 起作用,因为"this"是指一个依赖类.与我列出的其他方法相同.

this->n, since "this" refers to a dependent class, works. The same with the other methods I listed.

参考文献:

此处的常见问题解答: http://www.parashift.com/c ++-faq-lite/nondependent-name-lookup-members.html 此处的实时示例: http://ideone.com/nsw4XJ

Faq here: http://www.parashift.com/c++-faq-lite/nondependent-name-lookup-members.html Live example here: http://ideone.com/nsw4XJ

这篇关于如何继承带有模板的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆