本文内容来自于对狄泰学院 唐佐林老师 C++深度解析 课程的学习总结
类型转换函数
-
C++ 类中可以定义 类型转换函数
-
类型转换函数用于 将类对象转换为其它类型
-
语法规则:
Operator Type () { Type ret; //... return ret; }
编程实验
编写一个成员函数,将类类型转换成 int 类型
#include <iostream>
using namespace std;
class Test
{
private:
int m_value;
public:
Test()
{
;
}
Test(int value)
{
m_value = value;
}
int getValue()
{
return m_value;
}
operator int ()
{
return m_value;
}
};
int main()
{
Test t(1);
int i = t;
cout << "i = " << i << endl;
cout << "t.m_value = " << t.getValue() << endl;
return 0;
}
运行结果
实验结果:Test 类 对象 t 通过类型转换成员函数转换成了 int 类型,将成员变量 m_value 赋给了 int 类型的 i
- 类型转换函数
与转换构造函数具有同等的地位
使得编译器有能力 将对象转化为其它类型
编译器能够 隐式的使用 类型转换函数
- 编译器会 尽力尝试 让源码通过编译
实验编程
我们来写一个程序来实现类与类之间的转换
#include <iostream>
using namespace std;
class B
{
};
class A
{
private:
int m_value;
public:
A()
{
;
}
A(int value)
{
m_value = value;
}
operator B ()
{
B bTmp;
cout << "operator B " << endl;
return bTmp;
}
};
int main()
{
A atmp(100);
B btmp = atmp;
return 0;
}
运行结果
实验结果:通过调用A类的 operator B 成员函数,完成了A类对象向B类对象的类型转换
同时存在的问题
无法抑制隐式的类型转换函数调用
类型转换函数可能与转换构造函数冲突
工程中以 Type toType() 的公用成员代替类型转换函数
小结
C++ 类中可以定义 类型转换函数
类型转换函数用于 将类对象转换为其它类型
类型转换函数与 转换构造函数 具有同等的地位
工程中以 Type toType() 的公用成员代替类型转换函数