static_cast
该运算符把expression转化为type_name类型,static_cast在编译时使用类型信息执行转换,在转换执行必要时的检测(如指针越界,类型检查),但没有运行时类型检查来保证转换的安全性
- 用于基本类型检查,如把int转换为char,把int转换为enum
enum WeekType{
sun=0,Mon=1,Tues=2,Wed=3,Thus=4,Fir=5,Sat=6};
int main()
{
int a = 10;
char ch = 'x';
double dx = 12.34;
a = static_cast<int>(ch);
a = static_cast<int>(dx);
WeekType x = Mon;
a = x;
x = static_cast<WeekType>(a);
}
- 指针转换的限制
- 可以就void*转换为其它类型
int main()
{
int a = 10;
int* ip = nullptr;
double* dp = nullptr;
void* vp = &a;
ip = static_cast<int*>(vp);
dp = static_cast<double*>(dp);
return 0;
}
int main()
{
int a = 10, b = 20;
static_cast<void>(a + b);
}
class PtrInt
{
private:
int* pval; // new .heap ; stack . data;
public:
PtrInt(int* p = nullptr) :pval(p)
{
cout << "create Ptrint:" << this << endl;
}
~PtrInt()
{
delete pval;
pval = nullptr;
cout << "Destory Ptrin:t" << this << endl;
}
PtrInt(const PtrInt& it) :pval(new int(0)) //拷贝构造函数
{
*pval = *it.pval;
//*pval = it.*pval;
}
PtrInt& operator=(const PtrInt& it) //拷贝赋值函数
{
if (this != &it)
{
delete pval;
pval = new int(*it.pval);
//pval = it.pval;
}
cout << "Copy create Ptrint:" << this << endl;
return *this;
}
PtrInt(PtrInt&& it) :pval(it.pval) //移动构造函数
{
it.pval = nullptr;
cout << "move copy create Ptrint:" << this << endl;
}
PtrInt& operator=(PtrInt&& it) //移动赋值函数
{
if (this != &it)
{
delete[]pval;
pval = it.pval;
it.pval = nullptr;
}
cout << "Copy operator Ptrint:" << this << endl;
return *this;
}
};
PtrInt func(int x)
{
PtrInt tmp(new int(x));
return tmp;
}
int main()
{
PtrInt a(new int(10));
a = func(100);
return 0;
}
运行结果:
2.左值与右值之间的转换
#include<iostream>
using namespace std;
class PtrInt
{
private:
int</