dynamic_cast-显示类名

只对showname()操作,显示类名,问题来自伊世超

父类指针访问子类成员,dynamic_cast

#include <iostream>
using namespace std;

class father{
public:
	father(){};
	virtual ~father(){};
	void output(){cout<<"father"<<endl;}
};
class son: public father{
public:
	son(){};
	virtual ~son(){};
	void output(){cout<<"son"<<endl;}
};

void showname(father* x){
	son* pB = dynamic_cast<son*> (x); 
	if(pB!=0){
		pB->output();
	}
	else{
		x->output();
	}
}

int main(){
	father *f=new father();
	son *s=new son();
	father* x= new son();
	showname(x);
	showname(f);
	showname(s);
	return 1;
}
posted @ 2018-10-12 20:23  clq.lib  阅读(159)  评论(0)    收藏  举报