考虑以下因素:
#include <vector>
class Base
{
public:
Base() : x(0) {}
int x;
};
class Derived : public Base
{
public:
Derived(double z0) : Base(), z(z0) {}
double z;
};
class Foo
{
public:
// How to specify a default value for parameter vec0,
// consisting of two Base objects?
Foo(std::vector<Base> vec0 = ? ? ? ) : vec(vec0) {}
std::vector<Base> vec;
};
class Bar
{
public:
// foo1.vec needs to be initialized with two Base objects.
// foo2.vec needs to be initialized with two Derived objects.
Bar() : foo1(? ? ? ), foo2(? ? ? ) {}
Foo foo1;
Foo foo2;
};
int main()
{
Bar bar;
// Code here will want to use Base class pointers to access the elements
// in bar.foo1.vec and bar.foo2.vec.
}
如何在 Foo 构造函数中指定默认参数?
在
Bar
构造函数初始化列表中,如何指定Base
的 vectorfoo1
的对象,以及foo2
的Derived
对象 vector ?如何为该问题添加标题,以便其他需要解决该问题的人可以找到它?
最佳答案
@sklott的答案很好地解释了如何使用初始化列表来完成初始化。我想重点关注其中 Foo
的解决方案有一个指向 Base
的指针 vector 。使用std::vector<std::shared_ptr<Base>>
,您可以重写 @sklott 的解决方案,如下所示:
#include <memory> // std::shared_ptr
#include <utility> // std::move
class Foo
{
public:
Foo(std::vector<std::shared_ptr<Base>> vec0 = {
{ std::make_shared<Base>(), std::make_shared<Base>() }
}
)
: vec{ std::move(vec0) }
{}
std::vector<std::shared_ptr<Base>> vec;
};
class Bar
{
public:
Bar()
: foo1{} // calls Foo's default cont'r: initialized with two Base objects.
, foo2{ // initialized with two Derived objects.
{ std::make_shared<Derived>(1.0), std::make_shared<Derived>(1.0) }
}
{}
Foo foo1;
Foo foo2;
};
上面的代码将有 an undefied behaviour ,如果我们不提供virtual
Base
的析构函数类(class)。因此,要使其完整的解决方案:
class Base
{
public:
Base() : x(0) {}
int x;
virtual ~Base() = default; // don't forget to provide a virtual destructor
};
关于c++ - 如何使用 Base 和 Derived 对象默认初始化 std::vector<Base> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57389190/