使用带有显式构造函数 C++ 的初始值设定器列表初始化结构时出错

Error initialising struct with initialiser list with explicit constructor C++

提问人:Nitron_707 提问时间:7/28/2023 最后编辑:Nitron_707 更新时间:7/28/2023 访问量:51

问:

我有这样的结构

struct Example {
    Example() = default;

    explicit Example(const cv::Point2f& landmark,
                      float Score = 0.0f,
                      float visibilityScore = 1.f,
                      float threshold = 0.5f)
        : point(landmark),
          score(Score),
          visibilityScore(visibilityScore),
          threshold(visibilityThreshold) {}

    cv::Point2f point{0, 0};
    float score{0.0f};
    float visibilityScore{1.f};
    float threshold{0.5f};
};

当我尝试像下面一样单独初始化时,没有编译问题 -

Example eg = {};
eg.point = cv::Point2f(0,0);
eg.visibilityScore = 2.f;
eg.score = 3.f;
eg.threshold = 0.5f; 

当我尝试如下所示的括号初始值设定项列表时,出现构建错误 -

Example eg = {
.point = cv::Point2f(0, 0),
.score = 3.f,
.visibilityScore = 2.f,
.threshold = 0.5f};

错误-

no matching constructor for initialization of Example
note: candidate constructor not viable: cannot convert argument of incomplete type 'void' to 'const cv::Point2f' (aka 'const Point_<float>') for 1st argument
note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 4 were provided
note: candidate constructor not viable: requires 0 arguments, but 4 were provided

问题 - 这与第一个构造函数 arg 有关吗?explicitconst&

C++ 结构 初始值设定项列表

评论

3赞 UnholySheep 7/28/2023
指定的初始值设定项仅适用于聚合类型。由于您具有用户定义的构造函数,因此您的类型不是聚合类型
3赞 BoP 7/28/2023
代码尝试使用 Aggregate 初始化,但该类不是聚合(因为构造函数)。

答: 暂无答案