将指向相同派生 class 实例的任何指针向上转换为虚拟基指针将始终 return 相同地址? C++

Upcasting any pointer to the same derived class instance to a virtual base pointer will always return the same address? C++

我假设答案是肯定的,但我还没有针对每种可能的情况明确地找到这一点的断言。

给定一个复杂的继承树,由于中间非虚拟继承,可能需要逐步向上转换,并且在指针的多个向上转换链和向下动态转换链(总是从同一个实例开始)之后,最终地址到该实例的虚拟基础保证是相同的?

class A {};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};

class E{};
class F{};

class G : public D, public E{};
class H : public D, public F{};
class I : public G, public H{};

...

class X: ... {} //Some inheritance that has A as virtual base

//We start with pointers from an X type instance:
X x;
X* p_i = &x;

//We always end with A* pointers following different paths:
A* a_i = (A*) ...

我想我自己回答说“同一实例的虚拟基地址”显然应该是相同的。

但如果是这种情况并扩展问题,如果我们获得了相同的地址(仅通过转换)但使用不同的路径,我们是否会以与我们获得相同的这种情况“相似”的情况结束地址,但如果我们想使用最终指针,我们不能保证以定义的行为结束? Link to ccpreference where the following note is shown:

请注意,表示相同地址的两个指针可能仍然具有不同的值

struct C {
   int x, y;
} c;
 
int* px = &c.x;   // value of px is "pointer to c.x"
int* pxe= px + 1; // value of pxe is "pointer past the end of c.x"
int* py = &c.y;   // value of py is "pointer to c.y"
 
assert(pxe == py); // == tests if two pointers represent the same address
                   // may or may not fire
 
*pxe = 1; // undefined behavior even if the assertion does not fire

答案是肯定的。您应该尝试使用 C++ 风格的代码而不是 C 风格的代码。当您使用 C 风格时,您的代码无法获得可在 C++ 风格中使用的所有功能。这就是 C++ 存在的原因,它是面向对象的。 ;)

编辑:C 风格转换* 编辑:您可以使用 tutorialspoint 之类的东西来获得这方面的帮助!

  • 祝你有愉快的一天!