如何用模板继承类

how to inherit a class with templates?

本文关键字:继承 何用模      更新时间:2023-10-16

为什么以下操作会很好:

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

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

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

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

this->n,因为"this"指的是一个依赖类,所以有效。我列出的其他方法也是如此。


参考文献:

此处的传真:http://www.parashift.com/c++-faq lite/nondependent-name-lookup-members.html此处的示例:http://ideone.com/nsw4XJ