4个强制类型转换

static_cast   静态转换

dynamic_cast  动态转换

const_cast    去常性

reinterpret_cast  重新解释

一、static_cast

static_cast<目的类型>(表达式)
1.基本数据类型之间的转换
2.枚举类型之间的转换
3.指针类型转换成void*
4.将一个变量转换成常量
5.static_cast不能移除变量的const属性
6.基类和派生类之间的转换--
7.没有关系的类之间的转换

class A
{
public:
	void fn() { cout << "A::fn" << endl; }
};
class B
{
public:
	B(A& a) {}
	void gn() { cout << "B::gn" << endl; }
};
void main()
{
	A a;
	B b =static_cast(a); //B b(a)
	b.gn();
}
class A
{
public:
	void fn() { cout << "A::fn" << endl; }
	void gn() { cout << "A::gn" << endl; }
};
class B :public A
{
public:
	void fn() { cout << "B::fn" << endl; }
	void hn() { cout << "B::hn" << endl; }
};
void main()
{
	A a;
	B b;
	A* pa = &b;
	pa->fn();
	pa->gn();
	B* pb = static_cast(&a);
	pb->A::fn();
	pb->fn();
	pb->gn();
	pb->hn();
}
void main()
{
	const int cb = 20;
	//int* p = static_cast(&cb);
	int* p = const_cast(&cb);
	*p = 50;
	cout << cb << endl;
}
#if 0
void main()
{
	//int a = 20;
	//const int ca = static_cast(a);
	//cout << ca << endl;

}
#endif

#if 0
void main()
{
	int a = 10;
	int* p = nullptr;
	char ch = 'a';
	void* vp = &a;
	p = static_cast(vp); //ok
	cout << *p << endl;
	vp = &ch;
	p = static_cast(vp); //不安全
	cout << *p << endl;
}
#endif

#if 0
void main()
{
	//enum weekend {}
	enum AA { A = 3, B = 10 };
	enum BB { C = 5, D = 20 };
	int a = 10;
	enum AA aa = B;
	cout << aa << endl;
	aa = static_cast(a);
	cout << aa << endl;
	enum BB bb = C;
	aa =static_cast (bb);
	cout << aa << endl;
}
#endif

#if 0
void main()
{
	int a = 5;
	float b = 45.7;
/*	printf("%f\n", (float)a);
	printf("%d\n", (int)b);*/
	a = static_cast(b);
	char c = 'c';
	a = static_cast(c);
}
#endif

二、dynamic_cast
--将基类的指针或引用安全的转换成派生类的指针或引用,并用派生类的指针
或者引用来调用非虚函数
注意:当使用dynamic_cast时,该类型要包含有虚函数,才能进行转换,否则错误

class A
{
public:
	void print() { cout << "A::print" << endl; }
	virtual ~A() {}
};
class B :public A
{
public:
	void show() { cout << "B::show" << endl; }
};
void main()
{
	A* pa = new A;
	B* pb = dynamic_cast(pa);
	pb->print();
	pb->show();
}

三、reinterpret_cast适用于指针转换为另一种指针,转换不用修改指针变量值数据存储格式
(不改变指针变量值),只需要在编译时重新解释指针的类型即可
当然也可以将指针转换成整型值

#if 0
void main()
{
	float ff = 3.5f;
	float* pf = &ff;
	int* pi = reinterpret_cast(pf);
	cout << *pi << endl; //取不到正确的值
	cout << *pf << endl;

//	unsigned int a = -2;
//	printf("%u %d\n", a, a);
}
#endif


#if 0
class A
{
};
class B
{
};
void main()
{
	A* pa = new A;
	B* pb = reinterpret_cast(pa);
	//B *pb = (B*)pa

	int a = 10;
	int* pi = &a;
	long j = reinterpret_cast(pi);
	cout << j << endl; //地址值
}

你可能感兴趣的:(开发语言,c++)