转换构造函数
转换构造函数的作用是将一个其他类型的数据转换成一个类的对象。
当一个构造函数只有一个参数,而且该参数又不是本类的const引用时,这种构造函数称为转换构造函数。
转换构造函数是对构造函数的重载。
将double型的参数r转换成Complex类的对象,将r作为复数的实部,虚部为0。
Complex(double r)
{
real=r;
imag=0;
}
隐式转换
用户可以根据需要定义转换构造函数,在函数体中告诉编译系统怎样去进行转换。
//隐式转换
class Complex
{
private:
double real;
double imag;
public:
Complex(double r):real(r),imag(0){}; // 定义转换构造函数
void Print(){
cout<<"real = " << real <<" image = "<<imag<<endl;
}
Complex& operator+(Complex c){
return Complex(this->real + c.real, this->imag + c.imag);
}
};
int main()
{
Complex c;
c = 1.2; // 调用转换构造函数将1.2转换为Complex类型
c.Print();
return 0;
}
显示转换
通常是隐式的转换,如果想显式的转换需要在构造函数前添加explicit关键字
//显式转换
class Complex
{
private:
double real;
double imag;
public:
explicit Complex(double r):real(r),imag(0){}; // 定义转换构造函数
void Print(){
cout<<"real = " << real <<" image = "<<imag<<endl;
}
Complex& operator+(Complex c){
return Complex(this->real + c.real, this->imag + c.imag);
}
};
int main()
{
Complex c;
c = (Complex)1.2; // 调用转换构造函数将1.2转换为Complex类型
c.Print();
return 0;
}
不仅可以 将一个标准类型数据转换成类对象,也可以将 另一个类的对象转换成转换构造函数所在的类对象。
如可以将一个学生类对象转换为教师类对象,可以在Teacher类中写出下面的转换构造函数
Teacher(Student& s)
{
num=s.num;
strcpy(name,s.name);
sex=s.sex;
}
类型转换函数(强制类型转换的重载)
类型转换函数的作用是将一个类的对象转换成另一类型的数据。
- 类型强制转换运算符是单目运算符,也可以被重载,但只能重载为成员函数,不能重载为全局函数。
- 转换函数不能指定返回类型
- 转换函数不能有参数
如果已声明了一个Complex类,可以在Complex类中这样定义类型转换函数
operator double() //double类型的强制转换的重载
{
return real;
}
class Complex
{
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) :real(r), imag(i) {};
operator double() { return real; } //重载强制类型转换运算符 double
};
int main()
{
Complex c(1.2, 3.4);
cout << (double)c << endl; //输出 1.2
double n = 2 + c; //等价于 double n = 2 + c. operator double()
cout << n; //输出 3.2
}