c++ - 我如何让它调用正确的构造函数?

标签 c++ constructor default-constructor

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

S s[5]; // calls default constructor five times, one for each S object

但是如果我的类不是默认可解释的怎么办?我将如何实例化并稍后使用此数组?

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

S(int, int);

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

最佳答案

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)};

没有copy-ctor,你仍然可以使用下面的C++11 list-initialization -- as Andy Prowl指出 ctor 可能不是 explicit 的:

S arr[4] = {{1,1}, {1,2}, {1,3}, {1,4}};

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

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

std::array<S,4> arr = make_array();

关于c++ - 我如何让它调用正确的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16724064/

相关文章:

java - 错误: constructor Droid in class Droid cannot be applied to given types;

c++ - 重载新的运算符(operator)问题

c++ - 谁负责删除?

java - 将继承参数从父类(super class)更改为子类

c++ - C++ 中的空构造函数

c++ - 为什么我不能将 =default 用于带有成员初始值设定项列表的默认 ctors

python - 如何将 .npy 文件转换为 .binaryproto?

c++ - 使用boost图形库: how to create a graph by reading edge lists from file

java - 扩展抽象构造函数?

java - 构建hibernate实体时如何处理双向关系?