gpt4 book ai didi

c++ - 使用已分配的内存指向派生类指针的基类指针

转载 作者:行者123 更新时间:2023-11-30 00:55:05 26 4
gpt4 key购买 nike

取两个只能由new 创建的类。一类是基类,另一类是派生类。派生类只增加方法。

class Base
{};

class Derived : public Base
{};

Base * b = new Base{}
Derived * d = covert( b );

// - or -

Base * b = new Base{};
convert( b ); // converts Base to Derived
Derived * d = dynamic_cast<Derived *>(b);

我想做的是获取已分配的 Base 类数据,并通过某种方法或函数 convert 扩展/包装派生。

更新:为嵌入式系统构建内存是稀缺的,所以我正在尽我所能减少内存分配量。我只是想知道是否有一种方法可以扩展已经分配内存的基类并用派生类包装它。

更多更新:虽然嵌入式系统是 ARM,而且我目前使用的是 LLVM 编译器,但这在未来可能不是真的。因此,首选符合标准的方式。

最佳答案

如果我对你的问题的理解正确,一种可能的解决方案是使用聚合而不是继承。

class Base
{/*has only the data*/}

class Derived
{
Base &base;
Derived(Base &b) : base(b) {}
//now methods from derived will use the data members from instance passed in constructor
//if is possible the Derived needs to be a friend class of Base in case there are no getter for all members
}

如有必要,我们可以使用智能指针来代替引用。这样您就可以通过构造一个使用 Base 对象中的数据的新 Derived 对象来避免强制转换。

关于c++ - 使用已分配的内存指向派生类指针的基类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12973315/

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