从内置类型到自定义类的转换
我有一个自定义类,它充当一个名为 Integer 的 int,我想告诉编译器如何自动将某些类型转换为 Integer,这样我就可以避免一遍又一遍地输入相同的内容,
someCall(Integer(1), Integer(2));
这将成为
someCall(1,2);
我用谷歌搜索的但我所能做的find 是做相反的事情,将 Integer 转换为 int 我想完成相反的任务。
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));
would become
someCall(1,2);
I've googled but all I could find is to do the oposite, casting Integer to int I would like to accomplish the opposite.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编写一个采用
int
的构造函数,如下所示:如果类
Integer
有这个构造函数,那么你可以这样做:解释是,当你编写
f(1 )
,然后会自动调用采用int
类型的单个参数的Integer
构造函数并动态创建一个临时变量,然后该临时变量获取传递给函数!现在假设您想做完全相反的事情,即将
Integer
类型的对象传递给需要int
的函数:要使上述代码正常工作,您需要做的是,在类中定义用户定义的转换函数为:
因此,当您将
Integer
类型的对象传递给采用int
的函数时,就会调用转换函数并对象隐式转换为 int,然后作为参数传递给函数。您还可以这样做:Write a constructor that takes
int
, as:If the class
Integer
has this constructor, then you can do this:The explanation is that when you write
f(1)
, then the constructor ofInteger
that takes a single argument of typeint
, is automatically called and creates a temporary on the fly and and then that temporary gets passed to the function!Now suppose you want to do exactly the opposite, that is, passing an object of type
Integer
to a function takesint
:To make the above code work, all you need is, define a user-defined conversion function in the class as:
So when you pass an object of type
Integer
to a function which takesint
, then the conversion function gets invoked and the object implicity converts toint
which then passes to the function as argument. You can also do this:您可以在 Integer 中为要隐式转换的类型定义构造函数。不要让它们
显式
。You could define constructors in Integer for those types you want to implicitly convert. Do not make them
explicit
.纳瓦兹给出了正确答案。我只是想指出一些事情。
如果转换运算符不是 const,则无法转换 const 对象
最好将转换运算符声明为
Nawaz has given the correct answer. I just want to point out someting.
If the conversion operator is not const, you can't convert const objects
Better declare your conversion operator as