在我的例子:C++ - 上溯造型和向下轉換
在向上轉型,應該不是第二d.print()
調用印刷「基地」?
是不是「d」派生的對象上傳到基類對象?
而在向下轉換時,它有什麼優勢?
您能否以實際的方式解釋upcast和downcast?
#include <iostream>
using namespace std;
class Base {
public:
void print() { cout << "base" << endl; }
};
class Derived :public Base{
public:
void print() { cout << "derived" << endl; }
};
void main()
{
// Upcasting
Base *pBase;
Derived d;
d.print();
pBase = &d;
d.print();
// Downcasting
Derived *pDerived;
Base *b;
pDerived = (Derived*)b;
}
爲什麼你認爲'pBase'行應該改變'd.print();'的行爲?你的意思是詢問'pBase-> print();'? –