我正在尝试编写一个包装数值的 C++ 程序,我通过编写一个超类来做到这一点
它将处理两个简单函数和一个运算符重载函数。这是我的代码:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template <class T>
class Number {
protected:
T number;
public:
Number(T num) {
number = num;
}
string mytype() {
return typeid(number).name();
}
string what_am_i() {
ostringstream oss;
oss << "I am " << Number<T>::mytype() << " and my nanana is " << number;
return oss.str();
}
Number operator+ (Number an) {
Number brandNew = NULL;
brandNew.number = number + an.number;
return brandNew;
}
};
class MyInt : public Number<int> {
public:
MyInt() : Number<int>(0){};
MyInt(int num) : Number(num){
}
};
在 Main 函数中我想做类似的事情:
void main() {
MyInt three = 3;
MyInt two = 2;
MyInt five = three + two;
cout << five.what_am_i();
}
我的问题是三和二之间的加法,编译器说:
没有合适的用户定义的从“Number”到“MyInt”的转换
存在
我可以通过在 MyInt 中实现重载函数来解决这个问题,但由于我想支持许多类,如 MyShort 和 MyFloat,我想将其保留在超类中。有什么解决办法吗?
谢谢!
问题是当您从与当前类模板化相同的类继承时。继承的类型不会像您预期的那样被替换。例如,Number<int>
不会被替换为MyInt
对于继承的运算符+
.
运算符的返回值和入口参数+
is a Number<int>
, not a MyInt
。继承的类必须能够构造一个MyInt
from a Number<int>
。将下面的行放入MyInt
class:
MyInt(const Number<int> &x) : Number<int>(x) {}
为了避免额外的工作,最好不要继承Number
,但只是放一个typedef
for int
:
typedef Number<int> MyInt;
...然后其他一切都OK了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)