更新时间:2023-02-14 23:20:06
不,您不能访问由于
derived_int
是 Derived
的一部分,而 basepointer
是指向 Base
的指针。
No, you cannot access derived_int
because derived_int
is part of Derived
, while basepointer
is a pointer to Base
.
Derived* derivedpointer = new Derived;
derivedpointer->base_int; // You can access this just fine
派生类继承基类的成员,
Derived classes inherit the members of the base class, not the other way around.
但是,如果 basepointer
指向 Derived
然后你可以通过转换访问它:
However, if your basepointer
was pointing to an instance of Derived
then you could access it through a cast:
Base* basepointer = new Derived;
static_cast<Derived*>(basepointer)->derived_int; // Can now access, because we have a derived pointer
请注意,继承 public
第一个:
class Derived : public Base