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

C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
本文介绍了C++ 从基类指针访问派生类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

If I allocate an object of a class Derived (with a base class of Base), and store a pointer to that object in a variable that points to the base class, how can I access the members of the Derived class?

这是一个例子:

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 是指向 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:

Note that you'll need to change your inheritance to public first:

class Derived : public Base

这篇关于C++ 从基类指针访问派生类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)