首页 > 编程语言 > 详细

c++第十四章-(类型强转换)

时间:2014-07-13 12:33:01      阅读:305      评论:0      收藏:0      [点我收藏+]

类型强转换有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 << "这款产品!\n";
}
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 << "转换失败\n";
    }
    
    delete company;
    company = NULL;
    tecCompany = NULL;
    
    return 0;
}

控制台输出结果为:

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

c++第十四章-(类型强转换),布布扣,bubuko.com

c++第十四章-(类型强转换)

原文:http://www.cnblogs.com/huen/p/3837637.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!