如何用模板继承类
how to inherit a class with templates?
为什么以下操作会很好:
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
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 如何用数字处理log(0)
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 如何用转义符替换字符串中的所有特殊字符
- 如何用参数值调用函数(仅在运行时已知)
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 为什么模数运算符不适用于该代码
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 如何在C++中使用X509证书模在令牌中查找私钥
- 如何用模板继承类
- 如何用汇编语言编写模数(C++中的%)
- 如何用相同的参数从模板类继承到模板类