c++ - 如何使用 Base 和 Derived 对象默认初始化 std::vector<Base> ?

标签 c++ class c++11 inheritance stdvector

考虑以下因素:

#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.
}
  1. 如何在 Foo 构造函数中指定默认参数?

  2. Bar构造函数初始化列表中,如何指定Base的 vector foo1 的对象,以及 foo2Derived 对象 vector ?

  3. 如何为该问题添加标题,以便其他需要解决该问题的人可以找到它?

最佳答案

@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/

相关文章:

c++ - 如何在每次循环迭代期间生成一个 vector ,存储数据,然后删除该 vector ?

java - 如何在没有实例或类名的情况下获取类对象

c++ - 为什么 C++ 成员函数在参数中使用 &?

c++ - 带有 is_enum 的 enable_if 不起作用

c++ - 具有多重容器 C++ 11 的类的析构函数

c++ - 构造函数重载和默认参数

C++ 链接错误 : the compiler can not find the definition of the function

c++ - 数值回归测试

python - 为什么类的主体在定义时执行?

c++ - 如何将 QVariant 转换为自定义类?