Ste*_*eld 3 c++ operator-overloading
我正在尝试编写一个包装数值的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){
}
};
Run Code Online (Sandbox Code Playgroud)
在Main函数中我想做类似的事情:
void main() {
MyInt three = 3;
MyInt two = 2;
MyInt five = three + two;
cout << five.what_am_i();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是增加了三到两个,编译器说:
没有合适的用户定义的从"Number"到"MyInt"的转换
我可以通过在MyInt中实现重载函数来解决这个问题,但由于我想支持许多类,比如MyShort和MyFloat,我想把它留在Superclass中.有什么解决方案吗?谢谢!
问题是,当您从模板化类继承与您的模板相同时.继承的类型不会替换为您的期望.例如,Number<int>不会替换MyInt为继承的运算符+.
运算符的返回值和输入参数+是Number<int>不是MyInt,继承的类必须能够构建一个MyInt从Number<int>.在MyInt课堂上排在下面:
MyInt(const Number<int> &x) : Number<int>(x) {}
Run Code Online (Sandbox Code Playgroud)
为了避免这些额外的努力,最好不要继承,Number而只是 typedef为了int:
typedef Number<int> MyInt;
Run Code Online (Sandbox Code Playgroud)
......然后其他一切都还可以.