为了清楚起见,让我的新类(class)是:

class MyInt{
    public:
      MyInt(int x){theInt = x /10;}
      int operator+(int x){return 10 * theInt + x;}
    private
      int theInt;
};

假设我希望能够定义:
MyInt Three(30);
int thirty = Three;

但是为了得到这个结果,我在写:
MyInt Three(30);
int thirty = Three + 0;

如何从Custom类自动转换为内置类型?

最佳答案

具有类型转换功能:

class MyInt{
    public:
      MyInt(int x){theInt = x /10;}
      int operator+(int x){return 10 * theInt + x;}

      operator int() const { return theInt; } // <--

    private
      int theInt;
};

关于从自定义类到内置类型的转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18534548/

10-13 09:14