【问题标题】:how to inherit a class with templates? [duplicate]如何用模板继承一个类? [复制]
【发布时间】:2014-03-25 07:28:37
【问题描述】:

为什么以下方法可以正常工作:

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

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

【问题讨论】:

    标签: c++


    【解决方案1】:

    您需要使用“this”或“using”指令(或显式使用基类限定)对其进行限定。

    简而言之:该变量是非依赖类型不依赖于模板类的T),在查找非依赖类型的声明时,编译器不会查看依赖类型(您的 a)

    this-&gt;n,因为“this”指的是一个依赖类,所以有效。与我列出的其他方法相同。


    参考资料:

    常见问题解答:http://www.parashift.com/c++-faq-lite/nondependent-name-lookup-members.html 现场示例:http://ideone.com/nsw4XJ

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      相关资源
      最近更新 更多