我在使用虛擬方法時遇到問題。當我打電話f
它不起作用。爲什麼?爲什麼我的虛函數沒有被調用?
#include <iostream>
struct A {
virtual void f() const { std::cout << "In A"; }
virtual ~A() {};
};
struct B : A {
void f() const { std::cout << "In B"; }
};
int main()
{
A* a = new A();
B* b = dynamic_cast<B*>(a);
(*b).f();
delete a;
}
它根本不打印任何東西,我也沒有得到任何錯誤。我做錯了什麼?
總是檢查'dynamic_cast'的結果。 – chris
B是A,但A不是B. – Bart