C++的类型转换分为两种:显示转换和隐式转换
类型转换的场景:
①赋值转换
②函数调用参数传递时
③显式转换等等
隐式转换
class A {
public:
A(int x) : _x(x) {}
void print() { std::cout << _x << std::endl;}
private:
int _x;
};
int main()
{
A a = 4; // 隐式将int类型转换为自定义类类型
std::string str = "hello"; // 隐式将const char*类型转换为string类型
a.print();
}
显示转换
在构造函数前加上explicit禁止隐式转换,这时想要将其他类型转换为自定义类型就必须用强制类型转换
class A {
public:
explicit A(int x) : _x(x) {}
void print() { std::cout << _x << std::endl;}
private:
int _x;
};
int main()
{
A a = static_cast<A>(4); // 显式将int类型转换为自定义类类型
a.print();
}
类型转换函数
作用:实现由自定义类型向其他类型的转换
类型转换函数的形式一般为: operator 目标类型名()
用例:
class A {
public:
A(int x) : _x(x) {}
// 类型转换函数
operator int() { return _x;}
private:
int _x;
};
int main()
{
A a(4);
int val = a; // 调用类型转换函数
std::cout << val << std::endl;
}
注意:
①转换函数必须是成员函数,不能是友元形式
②转换函数没有返回值,但在函数体内必须用return语句以传值方式返回一个目标类型的变量
③转换函数不能有参数