创建一个对象数组,没有匹配的构造函数初始化错误

Create an array of objects, Error of no matching constructor initialization

本文关键字:构造函数 初始化 错误 一个对象 数组 创建      更新时间:2023-10-16

我正在尝试创建对象BuyOrder的数组

BuyOrder buy[10];

为什么我得到错误说"没有匹配的构造函数初始化的BuyOrder[10]"?

下面是BuyOrder构造函数。我必须创建另一个默认构造函数吗?

BuyOrder::BuyOrder(double price, int quantity, Stock &s)
    :buyPrice{ price },
    buyQuantity{quantity},
    buyStock{ s } 
    {}

就像我在评论中说的,你可以为小数组做聚合初始化。

#include <array>
struct example
{
    example(int, double) {}
    example(example const&) = delete;
};
int main() {
    example arr1[2] {
      {1, 3.4},
      {2, 5.6}
    };
    std::array<example, 2> arr2 {{
      {1, 3.4},
      {2, 5.6}
    }};
    return 0;
}