- /*************************************************************************
- > File Name: main.cpp
- > Author:
- > Mail:
- > Created Time: 2015年08月12日 星期三 16时48分34秒
- ************************************************************************/
- #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);
- //不合理
- //c = static_cast<Circle*>(base);
- delete base;
- delete c1;
- 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");
- /*
- dynamic_cast
- 有条件转换,动态类型转换,运行时类型安全检查(转换失败返回NULL):
- 1. 安全的基类和子类之间转换。
- 2. 必须要有虚函数。
- 3. 相同基类不同子类之间的交叉转换。但结果是NULL。
- */
- //苦于这个dynamic_cast一直成功不了,上语句 base = new Circle("c 12") 段错误,请大神指教.给跪了。
- //c = dynamic_cast<Circle*>(base);
- //delete base;
- //delete c;
- cout << "dynamic_cast over" << endl;
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/1408201513450.html
来源: http://www.codesnippet.cn/detail/1408201513450.html