定义:
类型转换操作符(type conversion operator)是一种特殊的类成员函数,它定义将类类型值转变为其他类型值的转换。转换操作符在类定义体内声明,在保留字 operator 之后跟着转换的目标类型。
函数原型
T1::operator T2() const
说明:
1. 转换函数必须是成员函数,不能指定返回类型,并且形参表必须为空;返回值是隐含的,返回值是与转换的类型相同的,即为上面原型中的T2;
2. T2表示内置类型名(built-in type)、类类型名(class type)或由类型别名(typedef)定义的名字;对任何可作为函数返回类型的类型(除了 void 之外)都可以定义转换函数,一般而言,不允许转换为数组或函数类型,转换为指针类型(数据和函数指针)以及引用类型是可以的;
3. 转换函数一般不应该改变被转换的对象,因此转换操作符通常应定义为 const 成员;
4. 支持继承,可以为虚函数;
5. 只要存在转换,编译器将在可以使用内置转换的地方自动调用它
举例:
#include <iostream>
using namespace std;
class D {
public:
D(double d) :d_(d) {}
operator int()const {
cout << "(int)d called!" << endl;
return static_cast<int>(d_);
}
private:
double d_;
};
int add(int a, int b) {
return a + b;
}
double fun(double a) {
return a;
}
int main() {
D d1 = 1.1;
D d2 = 2.2;
D d3 = 3.3;
/*
要想把d1,d2转换成int类型,得通过类型转换,此时自动调用
operator int()const函数
*/
cout << add(d1, d2) << endl;
cout << fun(d1) << endl;
system("pause");
return 0;
}
对于fun(d1),fun()函数的参数类型是double,而d1的类型是D,所以发生类型转换,此时,将d1转换成int类型,然后在转为fun()函数的参数类型double。如果没有类型转换函数,程序就会报错如下:
下面再看一个转换成类类型的例子:
#include <iostream>
using namespace std;
class A {
public:
A(int num = 0) :dat(num) {}
operator int() { return dat; }
private:
int dat;
};
class D {
public:
D(int num = 0):dat(num) {}
operator int() { return dat; }
operator A() {
A temp = dat;
return temp;
}
private:
int dat;
};
int main() {
D d = 22;
A a = 11;
int i;
i = d;//通过类型转换函数operator int()
cout << i << endl;
a = d;
cout << a << endl;//通过类型转换函数operator A()
system("pause");
return 0;
}
转换构造函数的概念:
转换构造函数就是把传入的其他类型参数转换成类的对象。
注意:
转换构造函数也是构造函数重载的一种,但是转换构造函数只能有一个参数,如果有多个参数就不是转换构造函数。原因:如果有多个参数,无法确认把哪一个参数转换成构造函数。
举例:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex()//默认构造函数
{
real = 0;
imag = 0;
cout << "调用默认构造函数" << endl;
}
Complex(double r, double i) :real(r), imag(i)//有参数的初始化构造函数,并用初始化表进行初始化
{
cout << "调用有参数的初始化构造函数" << endl;
}
Complex(double i)//转换构造函数,对传入的参数进行转换成对象
{
real = i;
imag = 0;
cout << "调用转换构造函数" << endl;
}
void Display()
{
cout << real << "+" << imag << "i" << endl;
}
private:
double real;
double imag;
};
int main()
{
Complex C1;
C1.Display();
Complex C2(1, 1);
C2.Display();
Complex C3(3);
C3.Display();
system("pause");
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/d035b66e60c182bfbbb7b3be14cbc6a6.png)