[英]How to inherit from Template class C++
Its been a while for C++, I have a class Number and several subclasses like Integer, Decimal.. I would like to override == operator to compare when two nums are numerically equal... I have something like the following, but can't seem to figure out the syntax for subclass inheriting from template class as well as syntax for overriding == operator in subclass... 对于C ++来说已经有一段时间了,我有一个Number类和几个子类,例如Integer,Decimal。我想重写==运算符以比较两个数字在数值上是否相等...我有类似以下内容的内容,但是可以似乎想出了从模板类继承的子类的语法以及子类中重写==运算符的语法...
template class <T>
class Number{
T data;
Number(T num) { data = num ;}
boolean operator==(T &other){ return data == other; }
}
class Integer : public Number{
int iData;
Integer(int i) { iData = i ; }
boolean operator==(Integer &other){ return idata == other.iData; }
}
You need to specify a specialization, like Number<int>
. 您需要指定一个特殊化,例如Number<int>
。 Otherwise you cannot inherit from a template, unless your derived class is a template itself. 否则,您不能从模板继承,除非您的派生类本身是模板。 There are some other errors in your code, like the ones mentioned in the comments, as well as the operator==
operator, which should take const Number<T>&
as a parameter. 您的代码中还有一些其他错误,例如注释中提到的错误以及operator==
运算符,应将const Number<T>&
作为参数。 So in your case use eg 所以在你的情况下使用例如
class Integer : public Number<int>
Once you do this, there is no need anymore for implementing the operator==
in the derived class, since it will be inherited. 完成此操作后,就不再需要在派生类中实现operator==
,因为它将被继承。 Full working code below: 完整的工作代码如下:
#include <iostream>
template <class T>
class Number
{
public:
T data;
Number(T num): data(num){}
bool operator==(const Number<T> &other) { return data == other.data; }
};
class Integer : public Number<int>
{
using Number<int>::Number; // inherit the constructor
};
int main()
{
Integer i1 = 10, i2 = 20;
std::cout << std::boolalpha << (i1 == i2);
}
either 要么
template<class T>
class Integer : public Number<T> {
or 要么
class Integer : public Number<int> {
depending on if you want Integer
to be a template too or not 取决于您是否也希望Integer
成为模板
Use 采用
template<class T>
class Number{
T data;
Number(T num) { data = num ;}
boolean operator==(T &other){ return data == other; }
};
template<typename T>
class Integer : public Number<T> {
int iData;
Integer(int i) { iData = i ; }
boolean operator==(Integer &other){ return idata == other.iData; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.