- #include <iostream>
- #include <string>
- class BaseClass
- {
- public:
- BaseClass(){}
- ~BaseClass(){}
- virtual void display()
- {
- std::cout << "base class" << std::endl;
- }
- };
- class DerivedClass: public BaseClass
- {
- public:
- DerivedClass(){}
- ~DerivedClass(){}
- void display()
- {
- std::cout << "derived class" << std::endl;
- }
- void display1()
- {
- std::cout << "derived calss display1" << std::endl;
- }
- private:
- };
- int main()
- {
- BaseClass *base = new BaseClass();
- base->display();
- DerivedClass *derived = new DerivedClass();
- derived->display();
- std::cout << "*******************************" << std::endl;
- BaseClass *bs1 = dynamic_cast<BaseClass*>(derived);
- bs1->display();
- DerivedClass *dr1 = dynamic_cast<DerivedClass*>(base);
- if(dr1 == NULL)
- {
- std::cout << "dr1 is null" << std::endl;
- }
- system("pause");
- return 0;
- }
运行结果
base class
derived class
*******************************
derived class
dr1 is null
父类指针转子类指针,结果为空
子类指针转父类指针,结果正常
阅读(1158) | 评论(0) | 转发(0) |