我有以下小程序:
#include #include using namespace std; class A { public: virtual void hello(int i) { cout << "A Hello " << i << endl; }; }; class B { public: virtual void nothing() = 0; }; class C : public A, public B { public: virtual void hello(int i) override { cout << "C Hello " << i << endl; }; virtual void nothing() override { cout << "C Nothing " << endl; } }; int main() { map map_; A* testA = new C(); map_[0] = (B*)testA; B* myB = static_cast(map_[0]); myB->nothing(); C* testC = new C(); map_[1] = (B*)testC; myB = static_cast(map_[1]); myB->nothing(); return 0; }
作为输出,我期待以下内容:
C Nothing C Nothing
但这是我得到的:
C Hello 0 C Nothing
因此调用了错误的函数:即使在代码中从未调用过hello(int i),也会调用它.我知道它与演员有关,但我无法理解错误在哪里.
为什么要调用hello(int i)?