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

标签 c++ c++11

取两个只能由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/

相关文章:

C++OpenGL : Ray Trace Shading Isn't Properly Shading

c++ - + 和++ 的运算符优先级

C++ 交互式命令行提示符,无需等待换行符

c++ - 当代码中不存在代码行时,如何解决 Visual Studio 2010 C++ 中的错误 C2719

c++ - 在 Ubuntu 16.04 下构建 Proxygen

C++ 不完整类型错误

c++ - 如何从自身加入 std::thread(在 C++11 中)

C++11 lambda 和参数包

c++ - 如何检查是否正在隐式生成移动构造函数?

c++ - enable_if 用于没有返回类型的函数