将父类类型的成员驻留在另一个类中

Residing a member of parent class type inside another class

本文关键字:另一个 父类 类型 成员      更新时间:2023-10-16
#include <iostream>
class BarParent
{
    virtual void fuz()
    {
        std::cout << "BarParent" << std::endl;
    }
};
class BarChild : public BarParent
{
    virtual void fuz()
    {
        std::cout << "BarChild" << std::endl;
    }
};
class Foo
{
// ??BarParent bar;??
public:
    Foo(BarParent bar);
};

我所寻求的是存储传递给构造函数的BarParent副本,并让它驻留在Foo中,同时仍然调用正确的virtual function

这是一个嵌入式应用程序:堆的使用令人反感。所以最好不要堆

SUMMARY:据所知,由于切片问题(长话短说,编译器无法确定泛型Bar的大小,等等,复制它的类型转换(,因此无法实现多态性。使用模板可能是个好主意,但是,它定义了多个classFoo<typename BarType>,因此,不可能执行function(如changeBar(BarParent)(,因为编译器会将其定义为仅为类Foo<Bartype>定义的changeBar(BarType)。如果有人有更好的主意,请告诉我。

我想我将不得不选择堆,或者const Barparent和指针。如果用户const_cast秒了,那么他是自讨苦吃,不是我的错!

class Foo
{
    BarParent* bar; //or std::unique_ptr<>
public:
    Foo(BarParent* barInst):bar(barInst){}
};

这将做你想做的事。你存储一个指向BarParent对象的指针,你可以用它来多态地(这是一个词吗?(调用虚拟函数。

您需要在构造函数之外(在堆上或其他位置(创建副本,并将指向它的指针传递给foo对象构造函数。或者,您可以实现克隆方法,如在复制派生实体时所讨论的,只使用基类指针,(无需彻底测试!(-C++

完全不同的方法是使用模板。。不过,它会给您留下多个foo<>类型。。如果您不打算重新分配bar对象,或者将所有foo存储在一个容器中,这可能是更好的选择,因为它不涉及堆

template<typename BarType>
class Foo
{
    BarType bar; //pointer not needed any more since we are storing the exact type.
public:
    Foo(BarType& barInst):bar(barInst){}
};

据我所知,如果没有对象切片,就无法优雅地处理这一问题。

我能想到的唯一方法是使用指针,并在"调用"Foo构造函数时创建一个副本:

class Foo
{
    BarParent* bar;
public:
    Foo(BarParent* b) : bar(b) {}
};
BarChild child;
Foo myFoo(new BarChild(child));
相关文章: