#include<iostream>
#include<string>
using namespace std;
//static_cast本质上就是明确隐式转换的,明确的作用
//基类与派生类之间的转换
class Cfather
{
public:
Cfather() {
m_ntest = 3;
}
virtual void foo() {
cout << "cfather::void foo()" << endl;
}
int m_ntest;
};
class Cson :public Cfather
{
virtual void foo() {
cout << "cson::void foo()" << endl;
}
};
class Cint
{
public:
operator int() {
return m_mint;
}
int m_mint;
};
int main()
{
int n = 5;
float f = 10.0f;
double dbl = 10.0f;
//本质上发生了隐式转换,但代码上体现的不明确
f = n;
//static_cast,将隐式转换明确
f = static_cast<float>(n);
//低风险的转换:都是允许的
//整形与浮点型,最多丢失精度(扩展精度),
n = static_cast<int>(dbl);
//字符与整形,也是精度问题
char ch = 'a';
n = static_cast<int>(ch);
//指针转换,void *指针的转换
void* p = nullptr;
int* p1 = static_cast<int*>(p);
//转换运算符的方式
Cint obj;
int k = static_cast<int>(obj);//如果类中没有提供转换运算符,
//那么编译不过,它无法将一个对象换换位int
cout << n << " " << f << endl;
//高风险的转换:
int kk;
char* p;
//整型与指针类型转换。隐式转换操作不了。
/*p = kk;*/
/*char* k = static_cast<char*>(kk);*///高风险的转换无论是隐式还是static_cast都不能成功
int* pk;
/*char* k = static_cast<char*>(pk);两种方法也是都不能转换*/
//基类与派生类之间的转换
Cfather* father = nullptr;
Cson* son = nullptr;
//父类转子类(不安全)
/*son = father;编译不能通过,*/
son = static_cast<Cson *>(father);//可以转换,不安全,没有提供运行时的检测。
//子类转父类(安全)
father = son;
father = static_cast<Cfather*>(son);//两个都可以转换
}