MOOC清华《面向对象程序设计》第4章:强制类型转换实验

#include <iostream>
using namespace std;

class B{
public:
	virtual void f() {}
};

class D : public B{};

class E{};

int main(){
	D d1;
	B b1;
	//d1 = static_cast<D>(b1);//ERROR:从基类无法转换回派生类
	b1 = static_cast<B>(d1);//OK!可以从派生类转换成基类
	//b1 = dynamic_cast<B>(d1);//ERROR:被转换的必须是引用或指针
	
	B* pB1 = new B();
	D* pD1 = static_cast<D*>(pB1);
	if(pD1) cout << "static_cast, B* --> D* : OK" << endl;
	if(!pD1) cout << "static_cast, B* --> D* : Failed" << endl;
	pD1 = dynamic_cast<D*>(pB1);
	if(pD1) cout << "dynamic_cast, B* --> D* : OK" << endl;
	if(!pD1) cout << "dynamic_cast, B* --> D* : Failed" << endl;
	
	D* pD2 = new D();
	B* pB2 = static_cast<B*>(pD2);
	if(pB2) cout << "static_cast, D* --> B* : OK" << endl;
	if(!pB2) cout << "static_cast, D* --> B* : Failed" << endl;
	pB2 = dynamic_cast<B*>(pD2);
	if(pB2) cout << "dynamic_cast, D* --> B* : OK" << endl;
	if(!pB2) cout << "dynamic_cast, D* --> B* : Failed" << endl;
	
	E* pE = dynamic_cast<E*>(pB1);
	if(pE) cout << "dynamic_cast, B* --> E* : OK" << endl;
	if(!pE) cout << "dynamic_cast, B* --> E* : Failed" << endl;
	
	//pE = static_cast<E*>(pB1);//ERROR:没有继承关系不能转换 
	
	//E e = static_cast<E>(pB1);//ERROR:没有提供转换途径 
	 
	return 0;
}

posted on 2017-10-05 18:17  sunshineman1986  阅读(113)  评论(0)    收藏  举报

导航