为了清楚起见,让我的新类是:C++ - 从自定义类转换为内建类型
比方说,我希望能够定义:
MyInt Three(30);
int thirty = Three;
但在为了得到这个结果我在写:
MyInt Three(30);
int thirty = Three + 0;
我怎么能从自定义类自动转换为内置类型?
为了清楚起见,让我的新类是:C++ - 从自定义类转换为内建类型
比方说,我希望能够定义:
MyInt Three(30);
int thirty = Three;
但在为了得到这个结果我在写:
MyInt Three(30);
int thirty = Three + 0;
我怎么能从自定义类自动转换为内置类型?
与类型转换功能:
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;
};
刚刚尝试过clang ++,它的工作! –
附加说明,这样做应该是透明的。也就是说,如果你转换为一个'int',那么这个类应该是一个数字类,而不是一些完全不相关的自定义类。 –
它应该是'const'(但也是'operator +',如果不是非成员函数的话),并且应该根据OP的怪异返回10 * theInt。 –
备注:它通常是一个_bad idea_通过非显式构造有_both_转换_implicit_(这里'int'->'MyInt' _and_'MyInt'-> 'int'通过转换运算符)。 (考虑例如'std :: string',其中有一个隐式转换_from_“const char *”(转换构造函数),而不是_to_“const char *”(为此,您需要调用'.c_str()'或)[另外,错字:'私人' - >'私人:'] –