不同数据类型间的转换(c++)
隐式类型转换
如:int i = 6;
i = 7.5 + i;
求解表达式时候的类型转换经历:(6→double)+7.5=13.5(→13)
显式类型转换
类型名(数据)
(类型名)数据(在c中多用到)
- 转换构造函数
将一个其他类型的数据转换为一个类的对象
需满足:
1.有且只有一个参数
2.是一个类的构造函数
3.参数类型是基本数据类型或者其他类的对象
将学生对象赋值给教师对象进行举例说明
将一个学生类对象转换为教师类对象再进行赋值
`#ifndef SMZQ_H_//smzq.h 类声明头文件
#define SMZQ_H_
class Student
{
public:
char* name;
public:
Student(const char* _name);
~Student();
void display();
};
class Teacher
{
public:
char* name;
public:
Teacher();
Teacher(const char*_name);
~Teacher();
Teacher(const Student& student1);//在教师类中声明转换构造函数,将学生类对象student1转换成教师类对象
void display();
};
#endif
#include"smzq.h"//函数声明文件 smzq.cpp
#include <iostream>
#include<string.H>
using namespace std;
Student::Student(const char* _name)
{
name = new char[strlen(_name) + 1];
strcpy_s(name, strlen(_name) + 1, _name);
cout << "Student(char *)" << endl;
}
Student::~Student()
{
cout << "~Student()" << endl;
}
Teacher::Teacher()
{
const char* name;
cout << "Teacher()" << endl;
}
Teacher::Teacher(const char*_name)
{
name = new char[strlen(_name) + 1];
strcpy_s(name, strlen(_name) + 1, _name);
cout << "Teacher(char *)" << endl;
}
Teacher::~Teacher()
{
cout << "~Teacher()" << endl;
}
Teacher::Teacher(const Student& student1)
{
name = student1.name;//函数体中告诉编译器怎么去实现转换
}
void Student::display()
{
cout << "name:" << name << endl;
}
void Teacher::display()
{
cout << "name:" << name << endl;
}
#include"smzq.h"//实现文件
#include <iostream>
using namespace std;
int main()
{
Teacher teacher1("张明");
Student student1("张和");
cout << "student:" << endl;
student1.display();
teacher1 = Teacher(student1);//将学生类对象student1转换成教师类对象并赋值给教师类对象teacher1
cout << "teacher:" << endl;
teacher1.display();
return 0;
}
运行结果: