[英]How to default-initialize std::vector<Base> with Base and Derived objects?
考虑以下:
#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
构造函数初始值设定项列表中 ,如何为foo1
指定一个Base
对象向量,为foo2
指定一个Derived
对象向量?
如何为这个问题加上标题,以便其他需要解决此问题的人可以找到它?
如何在Foo构造函数中指定默认参数?
只需使用初始化程序列表语法,即可显式声明包含元素:
class Foo {
public:
Foo(std::vector<Base> vec0 = {Base(), Base()}) : vec(vec0) {}
std::vector<Base> vec;
};
或隐式声明另一个初始化器列表:
class Foo {
public:
Foo(std::vector<Base> vec0 = {{}, {}}) : vec(vec0) {}
std::vector<Base> vec;
};
但是,如果您打算默认创建大小为2的列表,我认为最好这样做:
class Foo {
public:
Foo() : vec(2) {}
std::vector<Base> vec;
};
在Bar构造函数初始化器列表中,如何为foo1指定基础对象的向量,为foo2指定派生对象的向量?
你做不到 您需要使用模板或指针矢量。
模板示例:
template<class V>
class Foo {
public:
Foo(std::vector<V> vec0 = {{}, {}}) : vec(vec0) {}
std::vector<V> vec;
};
class Bar {
public:
// No need to explicitly initialize foo1
Bar() : foo2({{1.},{2.}}) {}
Foo<Base> foo1;
Foo<Derived> foo2;
};
@sklott的答案很好地说明了如何使用初始化列表进行初始化。 我想着重介绍Foo
具有指向Base
的指针向量的解决方案。 使用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;
};
如果我们不向Base
类提供virtual
析构函数,则上面的代码将具有未定义的行为 。 因此,要使其成为完整的解决方案:
class Base
{
public:
Base() : x(0) {}
int x;
virtual ~Base() = default; // don't forget to provide a virtual destructor
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.