c++ - 没有合适的用户定义转换

标签 c++ operator-overloading

我正在尝试编写一个包装数值的 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/

相关文章:

c++ - 可选参数 const 引用重新分配

c++ - 如何为 3D vector 重载 ostream 运算符?

c++ - 为成员函数中类的枚举成员重载运算符 <<

c++ - 如何避免实体和映射之间的循环依赖?

c++ - 如何使用 boost 可升级互斥量的示例

c++ - 从 std::ostream 重载 << 运算符时,为什么编译器会给出 "too many parameters for this operator function"错误?

c++ - 在哪里可以找到 .vcproj 文件结构的引用?

c++ - 用于插入集合的配对相等运算符重载

c++ - 在 C++ 中重载运算符 + 和 -

c++ - 取消引用运算符不起作用(语法问题?)