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

#include 
using namespace std;

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

class D : public B{};

class E{};

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

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

你可能感兴趣的:(C/C++,MOOC清华面向对象)