码迷,mamicode.com
首页 > 其他好文 > 详细

RTTI之dynamic_cast运算符

时间:2014-07-21 09:12:31      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:blog   http   os   2014   io   for   

#include <iostream>
#include <cstdlib>
#include <ctime>

using std::cout;
class Grand
{
	private:
		int hold;
	public:
		Grand(int h=0):hold(h){}
		virtual void Speak() const {cout << "I am a grand class!\n";}
		virtual int Value() const {return hold;}
};

class Superb:public Grand
{
	public:
		Superb(int h=0):Grand(h){}
		void Speak() const {cout << "I am a superb class!\n";}
		virtual void Say() const
		{
			cout << "I hold the superb value of " << Value() << "!\n";
		}
};

class Magnificent:public Superb
{
	private:
		char ch;
	public:
		Magnificent(int h=0, char c=‘A‘) : Superb(h),ch(c){}
		void Speak() const {cout << "I am a magnificent class!!!\n";}
		void Say() const {cout << "I hold the character " << ch << " and th e integer " << Value() << "!\n";}
};

Grand * Getone();

int main()
{
	std::srand(std::time(0));
	Grand * pg;
	Superb * ps;
	for(int i=0;i<5;i++)
	{
		pg=Getone();
		pg->Speak();
		if(ps=dynamic_cast<Superb *>(pg))
			ps->Say();
	}
	return 0;
}

Grand * Getone()
{
	Grand * p;
	switch(std::rand()%3)
	{
		case 0: p=new Grand(std::rand()%100);
				break;
		case 1:p=new Superb(std::rand()%100);
			   break;
		case 2:p=new Magnificent(std::rand()%100,‘A‘+std::rand()%26);
			   break;
	}
	return p;
}

bubuko.com,布布扣  

Superb * pm=dynamic_cast<Superb *>(pg)提出了这样的问题:指针pg的类型是否可被安全地转换为Superb *?如果可以,运算符将返回对象的地址,否则返回一个空指针。

RTTI之dynamic_cast运算符,布布扣,bubuko.com

RTTI之dynamic_cast运算符

标签:blog   http   os   2014   io   for   

原文地址:http://www.cnblogs.com/lakeone/p/3856366.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!