如何让它调用正确的构造函数?

use*_*677 5 c++ constructor default-constructor

当我创建一个像这样的用户定义类的数组时,它将默认构造每个元素:

S s[5]; // calls default constructor five times, one for each S object
Run Code Online (Sandbox Code Playgroud)

但是如果我的类不是默认构造的呢?我如何能够实例化并稍后使用此数组?

例如,我的类S可能不是默认构造的,但它确实有另一个这样的构造函数:

S(int, int);
Run Code Online (Sandbox Code Playgroud)

如何让它调用此构造函数而不是默认构造函数?

dyp*_*dyp 6

struct S
{
   const int m;
   S(int p, int k) : m(p) {}
};

S arr[4] = {S(1,1), S(1,2), S(1,3), S(1,4)};
Run Code Online (Sandbox Code Playgroud)

如果没有copy-ctor,你仍然可以使用下面的C++ 11列表初始化 - 正如Andy Prowl指出的那样,ctor可能不是explicit这样:

S arr[4] = {{1,1}, {1,2}, {1,3}, {1,4}};
Run Code Online (Sandbox Code Playgroud)

对于更具伸缩性的解决方案,您可以使用std::arraystd::vector:

std::array<S,4> make_array()
{
    // create array... and return
}

std::array<S,4> arr = make_array();
Run Code Online (Sandbox Code Playgroud)

  • 如果你是downvote,请发表评论.我只是检查了这个编译顺便说一句. (2认同)