我正在尝试编写一个包装数值的 C++ 程序,我通过编写一个父类(super class)来实现 它将处理两个简单函数和一个运算符重载函数。这是我的代码:
#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();
}
我的问题是三和二之间的加法,编译器说:
no suitable user-defined conversion from "Number" to "MyInt" exists
我可以通过在 MyInt 中实现重载函数来解决这个问题,但由于我想支持许多类,如 MyShort 和 MyFloat,我想将它留在父类(super class)中。有什么解决办法吗? 谢谢!
最佳答案
问题是当您从与当前类模板化相同的类继承时。继承的类型不会像您预期的那样被替换。例如,Number<int>
不会替换为 MyInt
对于继承的运算符 +
.
运算符的返回值和入口参数+
是 Number<int>
, 不是 MyInt
.继承的类必须能够构造一个 MyInt
来自Number<int>
.在 MyInt
的下面一行类:
MyInt(const Number<int> &x) : Number<int>(x) {}
为了避免额外的工作,最好不要继承Number
, 而只是放一个 typedef
对于 int
:
typedef Number<int> MyInt;
...然后其他一切正常。
关于c++ - 没有合适的用户定义转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22880493/