C++从基类指针访问派生类成员

标签 c++ inheritance pointers derived-class

如果我分配一个 Derived 类的对象(具有 Base 的基类),并将指向该对象的指针存储在指向基类的变量中类,如何访问 Derived 类的成员?

这是一个例子:

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_intDerived 的一部分,而 basepointer 是指向基础.

你可以反过来做:

Derived* derivedpointer = new Derived;
derivedpointer->base_int; // You can access this just fine

派生类继承基类的成员,而不是相反。

但是,如果您的 basepointer 指向 Derived 的实例,那么您可以通过强制转换访问它:

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++从基类指针访问派生类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2436125/

相关文章:

c++:如何避免 static_cast?

c++ - 将指针转换为函数类型

c - 返回 Void 指针截断值

java - 正确使用 Java 接口(interface)

c++ - 第 n 个斐波那契数的调用次数

c++ - opencv make error : limits. h 没有这样的目录文件

c++ - Qt 和 C++ - 未定义的插槽引用

C# - 使用子类实现接口(interface)

c - 在 C 中获取锯齿状数组的长度

c++ - 将数据从 vector 推回到 map 的 vector