从内置类型到自定义类的转换

Conversion from built in types to Custom Classes

本文关键字:转换 自定义 内置 置类型      更新时间:2023-10-16

我有一个自定义类,作为一个名为Integer的整型,我想告诉编译器如何自动将某些类型转换为Integer,这样我就可以避免一遍又一遍地输入相同的东西,

someCall(Integer(1), Integer(2));

将成为

someCall(1,2);

我已经搜索过了,但我所能找到的是做相反的事情,将Integer转换为int,我想完成相反的事情

写一个以int为参数的构造函数,如:

class Integer
{
   public:
       Integer(int);
};

如果类Integer有这个构造函数,那么可以这样做:

void f(Integer);
f(Integer(1)); //okay 
f(1);          //this is also okay!

解释是,当您编写f(1)时,然后Integer的构造函数(接受int类型的单个参数)被自动调用并动态创建一个临时对象,然后该临时对象被传递给函数!


现在假设您想要做完全相反的事情,即将Integer类型的对象传递给函数,接受int:

 void g(int); //NOTE: this takes int!
 Integer intObj(1);
 g(intObj); //passing an object of type Integer?
要使上述代码工作,所需要的只是在类中定义一个用户定义的转换函数:
class Integer
{
   int value;
   public:
       Integer(int);
       operator int() { return value; } //conversion function!
};

因此,当您将类型为Integer的对象传递给接受int的函数时,则调用转换函数并将对象隐式转换为int,然后将CC_10作为参数传递给函数。你也可以这样做:

int i = intObj; //implicitly converts into int
                //thanks to the conversion function!   

您可以在Integer中定义要隐式转换的类型的构造函数。

Nawaz给出了正确答案。我只是想指出一些事情。如果转换操作符不是const,则不能转换const对象

const Integer n(5);
int i = n; // error because non-const conversion operator cannot be called

最好将转换操作符声明为

operator int() const {return value;}