我在使用虚拟方法时遇到问题。当我打电话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