zoukankan      html  css  js  c++  java
  • RTTI之dynamic_cast运算符

    #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!
    ";}
    		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!
    ";}
    		virtual void Say() const
    		{
    			cout << "I hold the superb value of " << Value() << "!
    ";
    		}
    };
    
    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!!!
    ";}
    		void Say() const {cout << "I hold the character " << ch << " and th e integer " << Value() << "!
    ";}
    };
    
    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;
    }
    

      

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

  • 相关阅读:
    Nginx配置中运行与启动的详细介绍
    php实现文件上传进度条
    C# 提取逗号分割的字符串
    【sas proc sql】out join
    【SAS NOTE】substr函数
    【sas proc sql】子查询
    【SAS NOTE】数字字符互换
    【SAS NOTE】数组
    【sas Notel】merge
    【sas sql proc】inner join or outer join
  • 原文地址:https://www.cnblogs.com/lakeone/p/3856366.html
Copyright © 2011-2022 走看看