freeeyes 发表于 2015-12-31 08:50:57

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

首先声明两个类用于测试

#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 : publicShape
{
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;
}

页: [1]
查看完整版本: C中的几种类型转换const_cast,static_cast和dynamic_cast