zoukankan      html  css  js  c++  java
  • c++第十四章-(类型强转换)

    类型强转换有2种。

    class Company
    {
    public:
        Company(std::string theName,std::string theProduct);
        virtual void printInfo();
        
    protected:
        std::string name;
        std::string product;
    };
    
    Company::Company(std::string theName,std::string theProduct)
    {
        this->name = theName;
        this->product = theProduct;
    }
    
    void Company::printInfo()
    {
        std::cout << "这个公司的名字叫:" << name <<"正在生产" << product << std::endl;
    }
    
    
    class TechCompany : public Company
    {
    public:
        TechCompany(std::string theName,std::string theProduct);
        virtual void printInfo();
    
    };
    
    TechCompany::TechCompany(std::string theName,std::string theProduct) : Company(theName,theProduct)
    {
        
    }
    
    void TechCompany::printInfo()
    {
        std::cout << name << "公司大量生产了" << product << "这款产品!
    ";
    }
    int main(int argc, const char * argv[])
    {
        /*
        Company *company = new TechCompany("APPLE","IPHONE");
        //类型强转
        TechCompany *tecCompany = (TechCompany *)company;
         */
        
        Company *company = new Company("APPLE","IPHONE");
        //更安全的类型强转,转换失败返回NULL
        TechCompany *tecCompany = dynamic_cast<TechCompany *>(company);
        
        if (tecCompany != NULL)
        {
            tecCompany->printInfo();
        }
        else
        {
            std::cout << "转换失败
    ";
        }
        
        delete company;
        company = NULL;
        tecCompany = NULL;
        
        return 0;
    }

    控制台输出结果为:

    APPLE公司大量生产了IPHONE这款产品!

  • 相关阅读:
    洛谷P3799 妖梦拼木棒
    bzoj1008 [HNOI2008]越狱
    洛谷P3414 SAC#1
    洛谷P1078 文化之旅
    bzoj1053 [HAOI2007]反素数ant
    洛谷P1588 丢失的牛
    bzoj1085 [SCOI2005]骑士精神
    noip2016 蚯蚓
    noip2016 换教室
    html笔记03:表单
  • 原文地址:https://www.cnblogs.com/huen/p/3837637.html
Copyright © 2011-2022 走看看