找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 3011|回复: 0

C中的几种类型转换const_cast,static_cast和dynamic_cast

[复制链接]
 楼主| 发表于 2015-12-31 08:50:57 | 显示全部楼层 |阅读模式
首先声明两个类用于测试

#include<iostream>

using namespace std;
class Shape
{
public:
    string name;
    string *shape;
    Shape(string name){
        this->shape = new string("a dynamic shape");
        this->name = name;
        cout<<name<<"is a Shape" << endl;
    }
    virtual void foo()
    {
        cout <<" foo in shape" << endl;
    }
    virtual ~Shape(){
        delete this->shape;
        cout << this->name << "delete dynamic shape" << endl;
        cout<<this->name<<"is destoried as a shape"<<endl;
    }
};
class Circle : public  Shape
{
public:
    string *shape;
    string name;
    Circle(string name)
    :Shape(name)
    {
        this->shape = new string("dynamic circle");
        this->name = name;
        cout << name << "is a Circle"<< endl;
    }
    void foo()
    {
        cout << "foo in circle" << endl;
    }
    ~Circle()
    {
        delete this->shape;
        cout << this->name << "delete dynamic circle" << endl;
        cout << name << "is destoried as a circle" << endl;
    }
};


//测试代码
int main(void)
{
    //const_cast用于去掉const关键字,
    cout << "const_cast test" << endl;
    const int* const a = new int(3);
    cout << *a << endl;
    int *b = const_cast<int*>(a);
    *b = 5;
    delete b;
    cout << *a << endl;
    cout << "const_cast test over" << endl;

    //用static_cast把子类指针转化为父类指针,记得基类要虚析够哦
    //否则容易造成内存泄漏。
    cout << "static_cast test" << endl;
    Shape *base = new Shape("b");
    Circle* c= new Circle("c");
    Shape* b1 = base;
    Circle* c1;
    base = static_cast<Shape*> (c);

    delete base;
    delete c;
    cout << "static_cast text over"<< endl;

    //dynamic_cast用于把基类指针转化为子类指针,失败返回null,用于运行时类型检查(是不是的问题)
    cout << "dynamic_cast test" << endl;
    //下面这个代码circle的指针指向一个circle,这种实体就是circle,是转不成shape的,
    //c= new Circle("c");
     
    //下面这个代码,基类指针指向了子类
    base = new Circle("c 12");
    c = dynamic_cast<Circle*>(base);
    delete base;
    delete c;
    cout << "dynamic_cast over" << endl;
    return 0;
}


您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-3-29 09:41 , Processed in 0.012305 second(s), 6 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表