本文介绍了C ++ Access派生类成员从基类指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Base
{
public:
int base_int;
};
class Derived : public Base
{
public:
int derived_int
};
Base* basepointer = new Derived();
basepointer-> //Access derived_int here, is it possible? If so, then how?
推荐答案
不,您不能访问由于
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
这篇关于C ++ Access派生类成员从基类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!