将父类类型的成员驻留在另一个类中
Residing a member of parent class type inside another class
#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
的大小,等等,复制它的类型转换(,因此无法实现多态性。使用模板可能是个好主意,但是,它定义了多个class
和Foo<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));
相关文章:
- 从抽象类继承以创建另一个抽象类时,我应该重新声明所有虚函数吗?
- 两个抽象类,派生自同一个基类.如何访问从一个抽象类到另一个抽象类的指针
- C++多态性:如何测试一个类是否派生自另一个基类
- 派生类不能用另一个基类的成员重载基类中的私有成员
- 是否可以在引用另一个派生类的派生类中声明复制构造函数?
- 如何在 C 中包装C++具有参数的类方法或返回另一个C++类的实例?
- 如何将抽象类的可访问性限制为另一个抽象类及其子类?
- 将其转换为共享指针,并将其作为参数传递给另一个C++类
- 使用另一个模板类的嵌套名称说明符专用化模板类
- 从具有相同基数的另一个派生类调用派生类的非 const 方法
- 如何知道模板类中另一个模板类的类型
- 为什么当一个模板类继承自另一个模板类时,需要重新指定 typedef 并限定函数调用?
- 为什么将好奇模板模式的基类直接转换为另一个基类是错误的?
- 从基类(车辆)继承方法,从派生类(汽车)继承值,以使用 C++ 在另一个派生类(车道)中实现
- 调用对象类方法,该方法在另一个对象类中的向量中
- C :从一个基础到另一个基类模板的动态铸造
- 从抽象基类访问另一个基类成员
- "{"令牌 c++ 继承问题之前的另一个预期类名
- 多重继承.如何将 1 个父类的成员函数访问到另一个父类
- c++中的接口:为什么我需要一个接口类+另一个父类