类型转换构造函数 定义
//类型转换构造函数:
//只有一个参数的构造函数,
//且参数不是自己的const 引用的构造函数,也称之为 :类型转换构造函数。
//类型转换构造函数:
//只有一个参数的构造函数,
//且参数不是自己的const 引用的构造函数,也称之为 :类型转换构造函数。
class Teacher88 {
public:
Teacher88() {
cout << "Teacher88 consturct using" << endl;
}
//Teacher88也叫做 类型转换构造 函数
Teacher88(int age):m_age(age) {
cout << "Teacher88 int consturct using" << endl;
}
void printf() {
cout << "m_age = " << this->m_age << endl;
}
Teacher88(Teacher88 & obj) {
this->m_age = obj.m_age;
cout << "Teacher88 copy consturct using" << endl;
}
private:
int m_age;
};
void main(){
Teacher88 t1; //正常构造一个Teacher88,命名为t1
t1.printf();
Teacher88 t2(20);//正常构造一个Teacher88,命名为t2
t2.printf();
Teacher88 t3 = 80;//类型转换构造函数调用 。实际上 这里存在隐式的类型转换,只是会调用 copy 构造函数
t3.printf();
}
类型转换函数
1. const 是可选项,表示不应该改变待 转换 对象的内容
2. type 表示要转换成的某种类型 --这里对应double
3. 没有参数传递,没有返回类型
4.但是确能返回一个type类型的值
5.必须定义为类的成员函数
6 static_cast也是会调用 operator double()
//类型转换构造函数:
//只有一个参数的构造函数,
//且参数不是自己的const 引用的构造函数,也称之为 :类型转换构造函数。
class Teacher88 {
public:
Teacher88() {
cout << "Teacher88 consturct using" << endl;
}
//Teacher88也叫做 类型转换构造 函数
Teacher88(int age):m_age(age) {
cout << "Teacher88 int consturct using" << endl;
}
void printf() {
cout << "m_age = " << this->m_age << endl;
}
Teacher88(Teacher88 & obj) {
this->m_age = obj.m_age;
cout << "Teacher88 copy consturct using" << endl;
}
//类型转换函数
//1. const 是可选项,表示不应该改变待 转换 对象的内容
//2. type 表示要转换成的某种类型 --这里对应double
//3. 没有参数传递,没有返回类型
//4.但是确能返回一个type类型的值
//5.必须定义为类的成员函数
operator double() const {
return m_score;
}
void setScore(double score) {
this->m_score = score;
}
private:
int m_age;
double m_score;
};
void main(){
Teacher88 t3 = 80;//类型转换构造函数调用 。实际上 这里存在隐式的类型转换,只是会调用 copy 构造函数
t3.printf();
//类型转换函数调用
t3.setScore(99.8);
cout << t3 + 9 << endl;//结果为:108.8 。隐式调用
cout << t3.operator double() + 10 << endl; //结果为 109.8 显示调用
static_cast<double>(t3); // static_cast也是会调用 operator double()
cout << "duandian" << endl;
}