#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
}
这是一个嵌入式应用程序:对堆的使用不屑一顾。所以最好不要堆
摘要:据我们所知,由于slicing problem(长话短说,编译器无法确定通用Bar
的大小等等,因此无法完成。在复制它类型转换),所以无法实现多态。使用模板可能是一个好主意,但是,它定义了多个class
es Foo<typename BarType>
,因此,执行function
(例如changeBar(BarParent)
)是不可能的,因为编译器会将此定义为仅为类changeBar(BarType)
定义的Foo<Bartype>
。如果有人有更好的想法,请告诉我。
我想我必须去堆,或const Barparent
和指针。如果用户const_cast
,那他就是在寻找麻烦,而不是我的错!
答案 0 :(得分:2)
class Foo
{
BarParent* bar; //or std::unique_ptr<>
public:
Foo(BarParent* barInst):bar(barInst){}
};
这将做你想要的。您存储指向BarParent
对象的指针,您可以使用它来多态(是一个单词?)调用虚函数。
您需要在构造函数外部(在堆上或其他位置)创建副本,并将指针传递给foo
对象构造函数。或者,您可以实现Copying derived entities using only base class pointers, (without exhaustive testing!) - 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){}
};
答案 1 :(得分:0)
我没有办法在没有object slicing的情况下优雅地处理这个问题。
我能想到的唯一方法是使用指针,并在“调用”Foo
构造函数时创建一个副本:
class Foo
{
BarParent* bar;
public:
Foo(BarParent* b) : bar(b) {}
};
BarChild child;
Foo myFoo(new BarChild(child));