从内置类型到自定义类的转换 [英] Conversion from built in types to Custom Classes

查看:90
本文介绍了从内置类型到自定义类的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类,它充当一个称为Integer的int,我想告诉编译器如何自动将某些类型转换为Integer,这样我就可以避免一遍又一遍地键入相同的内容,

I have a custom class that acts as an int called Integer, I would like to tell compiler how to convert certain types to Integer automatically so that I can avoid typing same thing over and over again,

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

将成为

someCall(1,2);

我已经在google上搜索过,但我能找到的只是做相反的事情,将Integer转换为int

I've googled but all I could find is to do the oposite, casting Integer to int I would like to accomplish the opposite.

推荐答案

写一个采用 int 的构造函数,例如:

Write a constructor that takes int, as:

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

如果类 Integer 具有此构造函数,那么您可以执行以下操作:

If the class Integer has this constructor, then you can do this:

void f(Integer);

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

原因是当您写 f(1),然后会自动调用 Integer 的构造函数,该构造函数接受单个类型为 int 的参数。临时,然后将该临时传递给函数!

The explanation is that when you write f(1), then the constructor of Integer that takes a single argument of type int, is automatically called and creates a temporary on the fly and and then that temporary gets passed to the function!

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

Now suppose you want to do exactly the opposite, that is, passing an object of type Integer to a function takes int:

 void g(int); //NOTE: this takes int!

 Integer intObj(1);
 g(intObj); //passing an object of type Integer?

要使上述代码正常工作,您需要做的是,在类为:

To make the above code work, all you need is, define a user-defined conversion function in the class as:

class Integer
{
   int value;
   public:
       Integer(int);
       operator int() { return value; } //conversion function!
};

因此,当您传递 Integer 转换为使用 int 的函数,然后转换函数被调用,对象隐式转换为 int 然后传递该函数作为参数。您也可以这样做:

So when you pass an object of type Integer to a function which takes int, then the conversion function gets invoked and the object implicity converts to int which then passes to the function as argument. You can also do this:

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

这篇关于从内置类型到自定义类的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆