gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:35:25 26 4
gpt4 key购买 nike

如果我分配一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com