从内置类型到自定义类的转换
Conversion from built in types to Custom Classes
我有一个自定义类,作为一个名为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;}
相关文章:
- 将文件复制到自定义位置,存在字符串转换问题
- C++ 通过自定义赋值运算符隐式转换函数参数
- 类型转换自定义结构
- 自定义类型转换运算符在转发引用上调用时不起作用(当对象按值传递时有效)
- 将字符串转换为自定义类
- 自定义函数转换错误?
- 将 OpenGL 坐标系统转换为自定义并返回
- 如何将CString转换为使用WCHAR的Windows API和自定义函数?
- 如何在<typename> <long> 不更改给定代码的情况下将自定义向量与 STL 向量相互转换?
- 使用自定义转换运算符的不明确性
- 如何支持any_cast将自定义类强制转换为字符串
- PyQt5:使用自定义信号时 int 对象的错误转换
- 自定义Clang将C 代码转换为C
- 自定义文本到语音转换中的语音
- C 功能指针用于将QVariant转换为{自定义类型
- 使用自定义分配器和std ::向量的std ::向量子类之间的转换
- 如何重写 AcDbEntity::transformBy 以在移动或缩放时获取自定义实体转换
- 不允许对自定义类型进行多次隐式转换?
- 可视类型转换自定义 C++ 类
- 如何在VS2012中转换自定义类型为字符串