static_cast 和 dynamic_cast 的区别

本文很多题目都是来源用于网上,如有侵权,请及时通知。和别人不同的是,有些题目加上了自己的思考。标记为【Jacob】

第一部分:简答题

1. 一下C++中static_cast 和 dynamic_cast 的区别。

答:static_cast 用于有比较明确定义的变换,包括不需要强制转换的变换。

【others】

l  dynamic_cast 适用于类型安全的向下转换,常用在继承中的父类指针向子类指针的转换。若转换成功则返回改类型的指针,若失败,则返回NULL。

【Jacob】

l  如果指针实际指向子类,

        但是声明称父类的指针,

            如果父类没有virtual函数,编译错位。

            如果父类有virtual函数,转化成功。

l  如果真正指向的类是父类,

        如果父类没有virtual函数,编译错误。

        如果父类有virtual函数,转化成功,但是转化完的指针是空。

       ==================================================

        has virtual

      ===================================================

class Parent {
public:
Parent() { cout << "Parent()\n"; };
virtual ~Parent() { cout << "~Parent()\n"; }
};
class Child :public Parent {
public:
Child() { cout << "Child()\n"; };
~Child() { cout << "~Child()\n"; }
};
cout << "dynamic_cast()---------------\n";
Parent* pP2 = new Child(); // 先调用父类的构造函数,然后调用子类的构造函数
// Parent() Child()
Parent* pPYes2 = new Parent(); // Parent()
Child* pC;
pC = dynamic_cast<Child*>(pP2);    // OK pC Not NULL
if (pC) cout << "pC = dynamic_cast<Child*>(pP2) OK" << endl;
pC = dynamic_cast<Child*>(pPYes2); // OK pC == NULL;
if(!pC) cout << "pC = dynamic_cast<Child*>(pP2) OK,but pC is NULL" << endl;
delete pP2; // ~Child(); ~Parent();
delete pPYes2; // ~Parent();

==================================================

       no virtual

      ===================================================

class Parent {
public:
Parent() { cout << "Parent()\n"; };
~Parent() { cout << "~Parent()\n"; }
};
class Child :public Parent {
public:
Child() { cout << "Child()\n"; };
~Child() { cout << "~Child()\n"; }
};
cout << "dynamic_cast()---------------\n";
Parent* pP2 = new Child(); // 先调用父类的构造函数,然后调用子类的构造函数
// Parent() Child()
Parent* pPYes2 = new Parent(); // Parent()
Child* pC;
pC = dynamic_cast<Child*>(pP2);    // compile error!
if (pC) cout << "pC = dynamic_cast<Child*>(pP2) OK" << endl;
pC = dynamic_cast<Child*>(pPYes2); // compile error!
if(!pC) cout << "pC = dynamic_cast<Child*>(pP2) OK,but pC is NULL" << endl;
delete pP2; // ~Child(); ~Parent();
delete pPYes2; // ~Parent();

   【Jacob】 为什么没有virtual 会编译失败,我想没有virtual的话的,编译器认为这个类没有多态,根本不可能转换成子类可能,所有报编译错误。  

猜你喜欢

转载自blog.csdn.net/bjzhaoxiao/article/details/80062763
今日推荐