1.普通类型转类类型
需求:
Human boy1 =10000; //薪资 可以用构造函数Human(int)构造函数实现
Human boy2 = 张三"; //姓名 可以用构造函数Human(char *)构造函数实现
#include<string>
#include<iostream>
class boy {
public:
boy(int salare);
boy(const char* name);
~boy();
void description();
private:
int salare;
char* name;
};
//boy(int)构造函数
boy::boy(int salare) {
const char* name = "name为空";
this->name = new char[strlen(name) + 1];
strcpy_s(this -> name, strlen(name) + 1, name);
this->salare = salare;
}
//boy(const char *)构造函数
boy::boy(const char* name) {
this->salare = 0;
this->name = new char[strlen(name) + 1];
strcpy_s(this->name, strlen(name) + 1, name);
}
boy::~boy() {
delete[] this->name;
}
void boy::description() {
std::cout << "姓名:" << this->name << std::endl;
std::cout << "薪资:" << this->salare << std::endl;
}
int main() {
boy boy1 = 10000;
boy boy2 = "Jack";
boy1.description();
boy2.description();
system("pause");
return 0;
}
2.类类型转普通类型
调用特殊的运算符重载函数,类型转换函数,不需要写返回类型
类型转换函数:operator 普通类型();
需求:
Boy boy1(“Jack”, 10000);
int salare= boy1; // salare;
char *name = boy1; // “Jack”
#include<string>
#include<iostream>
class boy {
public:
boy(const char* name, int salare);
~boy();
//转int 类型 也可以不加const
//类型运算符重载,不需要返回类型
operator int() const;
operator char* ()const;
private:
int salare;
char* name;
};
//直接返回类型
boy::operator int()const {
return this->salare;
}
//直接返回类型
boy::operator char* ()const {
return this->name;
}
boy::boy(const char* name, int salare) {
if (!name) {
name = "name为空";
}
this->name = new char[strlen(name) + 1];
strcpy_s(this->name, strlen(name) + 1, name);
this->salare = salare;
}
boy::~boy() {
delete[] this->name;
}
int main() {
boy boy1("Jack", 10000);
int salare = boy1;
char* name = boy1;
std::cout << "姓名:" << name << "薪资:" << salare << std::endl;
system("pause");
return 0;
}
3.类类型转类类型
调用对应的构造函数,参数类型就是类A
实例:
把Boy类型,转换为Man类型
#include<string>
#include<iostream>
class boy {
public:
boy(const char* name, int salare);
operator char* ()const;
~boy();
private:
int salare;
public:
char* name;
};
boy::boy(const char* name, int salare) {
if (!name) {
name = "name为空";
}
this->name = new char[strlen(name) + 1];
strcpy_s(this->name, strlen(name) + 1, name);
this->salare = salare;
}
boy::operator char* ()const {
return this->name;
}
boy::~boy() {
delete[] this->name;
}
class Man {
public:
Man(const boy* boy);
~Man();
char* name;
};
Man::Man(const boy* boy) {
this->name = new char[strlen((char*)*boy + 1];
strcpy_s(this->name, (char*)*boy + 1, boy->name);
}
Man::~Man() {
delete[]this->name;
}
int main() {
boy boy1("Jack", 10000);
Man man1 = &boy1;
std::cout << man1.name<<std::endl;
system("pause");
return 0;
}