下面的代碼的執行產生這樣的輸出:的dynamic_cast
1 is a null pointer
2 is not a null pointer
代碼
class base {};
class derived1: public base {};
class derived2: public base {};
int main() {
base *baseptr[1];
baseptr[0] = new derived2;
derived1 *derptr = new derived1;
derived1 *derivedptr1 = dynamic_cast<derived1*>(baseptr[0]);
derived1 *derivedptr2 = dynamic_cast<derived1*>(derptr);
cout<<((derivedptr1==0)?"1 is null pointer":"1 is not a null pointer") << endl;
cout<<((derivedptr2==0)?"2 is null pointer":"2 is not a null pointer") << endl;
}
爲什麼derivedptr2僅初始化和derivedptr1是不是?因爲兩者都有一個有效的右手邊值。這是否與動態演員有關,並且在第二種情況下,我將derived1 *轉換爲derived1 *?
請首先解釋一下您對輸出的疑惑或奇怪。 – 2011-06-04 05:12:04
爲什麼在標題中包含'static_cast',實際問題甚至沒有提到'static_cast'? – AnT 2011-06-04 05:27:42