D
不继承自A
(并且A
不继承自D
),也不是其同级兄弟之一,因此您不能将一种类型的指针强制转换为另一种指针。
我具有以下类体系结构:
class A{ public: A() {} virtual ~A() {} void printA() { cout << "A" << endl; } }; class B{ public: B() {} virtual ~B() {} void printB() { cout << "B" << endl; } }; class C : public A{ public: C() : A() {} virtual ~C() {} void printC() { cout << "C" << endl; } }; class D : public B{ public: D() : B() {} virtual ~D() {} void printD() { cout << "D" << endl; } }; class P: public C, public D{ public: P() : C(), D() {} ~P() {} void printP() { cout << "P" << endl; } };
问题是,在Visual Studio中,某些强制转换会失败,但是在联机编译器中,一切正常。我将在代码中更好地解释问题:
A* pObject= new P(); // let s say I have this instance of type P referenced by an A type pointer dynamic_cast<P*>(pObject)->printP(); // works fine in both VS and online compiler, as expected dynamic_cast<D*>(pObject)->printD(); // THIS IS THE PROBLEM, in Visual Studio cast returns nullptr, but in online compiler works fine. return 0; }
您知道此行为的任何解决方案/原因吗?谢谢。
我具有以下类体系结构:类A {public:A(){} virtual〜A(){} void printA(){cout <
D
不继承自A
(并且A
不继承自D
),也不是其同级兄弟之一,因此您不能将一种类型的指针强制转换为另一种指针。
D
不继承自A
(并且A
不继承自D
),也不是其同级兄弟之一,因此您不能将一种类型的指针强制转换为另一种指针。