1、用于基本类型的转换,不能用于基本类型指针间的转换
虽然不能作用于基本类型指针,但是可以作用于void* 指针的转换。
#include <iostream>
using namespace std;
int main()
{
int i = 0x12345;
char c = 'c';
int* pi = &i;
char* pc = &c;
c = static_cast<char>(i); //将int类型转化为char类型
cout << c << endl;
//pc = static_cast<char*>(pi); //error
float fNum = 2.345;
void* pv = &fNum;
float * fp = static_cast<float *>(pv); //转化void * 指针
cout << *fp << endl;
return 0;
}
运行结果
E
2.345
2、用于有继承关系类对象之间的转换和类指针之间的转换
#include <iostream>
using namespace std;
class Parent
{
};
class Child : public Parent
{
};
class Other
{
};
int main()
{
Parent parent;
Child child;
Other other;
Parent *p1 = static_cast<Parent *>(&child); //这两种写法没问题 但是结果无法预估
Child *p2 = static_cast<Child *>(&parent);
//此段代码无法通过编译 “static_cast” : 无法从“Child *”转换为“Other *” 因为Other类和Child类没有继承关系
//Other *p3 = static_cast<Other *>(&child);
return 0;
}
3、用于使用explict修饰的构造函数
#include <iostream>
#include <string>
using namespace std;
class Test
{
int mValue;
public:
Test()
{
mValue = 0;
}
//explicit 参数用于杜绝编译器的隐式转换
explicit Test(int i) // 一个参数的构造函数被称为转换构造函数
{
mValue = i;
}
Test operator + (const Test& p)
{
Test ret(mValue + p.mValue);
return ret;
}
int value()
{
return mValue;
}
};
int main()
{
Test t;
//t = 5 这种写法将会直接报错
t = static_cast<Test>(5); //等效于 t = Test(5);
Test r;
r = t + static_cast<Test>(10); //等效于 r = t + Test(10);
cout << r.value() << endl;
return 0;
}
运行结果
15