相关内容:
类型转换操作符(type conversion operator
)是一种特殊的类成员函数,它定义将类类型值转变为其他类型值的转换。转换操作符在类定义体内声明,在保留字 operator
之后跟着转换的目标类型。函数原型:
1 | T1::operator T2() [const]; //T1的成员函数,"(T2)a"类型转换 |
- 转换函数必须是成员函数,不能指定返回类型,并且形参表必须为空;返回值是隐含的,返回值是与转换的类型相同的,即为上面原型中的T2;
- T2表示内置类型名(built-in type)、类类型名(class type)或由类型别名(typedef)定义的名字;对任何可作为函数返回类型的类型(除了 void 之外)都可以定义转换函数,一般而言,不允许转换为数组或函数类型,转换为指针类型(数据和函数指针)以及引用类型是可以的;
- 转换函数一般不应该改变被转换的对象,因此转换操作符通常应定义为 const 成员;
- 支持继承,可以为虚函数;
- 只要存在转换,编译器将在可以使用内置转换的地方自动调用它;
代码相关内容:
转换函数:operator int() const;
注意: - 必须是成员函数;
- 不能指定返回类型;
- 形参列表必须是空的;
- 必须显式的返回一个指定类型的值;
- 不应该改变被转换对象,通常定义为
const
;1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using namespace std;
class Dog
{
public:
Dog(string n, int a, double w):name(n),age(a),weight(w){}
operator int() const // 转换函数;
{
return age; // 此处转换操作符的函数返回值必须是整型;
}
operator double() const // 转换函数;
{
return weight; // 此处转换操作符的函数返回值必须是整型;
}
private:
int age;
double weight;
string name;
};
int main()
{
int a, b;
double c = 0.0;
a = 10;
b = a;
Dog d("Bill",6,15.0);
// 调用第一个转换函数;
b = d;
cout << b << endl;
// 调用第二个转换函数
c = d;
cout << c << endl;
return 0;
}代码执行结果:
参考链接:
C++类型转换操作符(type conversion operator)