#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
s,那他是自找麻烦,又不是我的错!
最佳答案
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){}
};
关于c++ - 驻留在另一个类中的父类类型的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14767204/