正在使默认构造函数和初始值设定项列表并行工作

Getting default constructor and initializer list to work side by side

本文关键字:列表 工作 并行 默认 构造函数      更新时间:2023-10-16

我一直在使用初始值设定项列表来实例化结构的实例,但现在想添加一个默认构造函数。

struct Size {
    unsigned int width;
    unsigned int height;
};
void SizeFunc(Size const &size) { }
int main() {
    SizeFunc({1024, 768});   // OK.
}

不幸的是,在使用初始值设定项列表进行实例化时,添加默认构造函数会导致错误。

struct Size {
    Size() : width(1920), height(1080) { }
    unsigned int width;
    unsigned int height;
};
void SizeFunc(Size const &size) { }
int main() {
    Size size; // OK.
    SizeFunc({1024, 768});    // error: no matching function for call to
                              // 'Size::Size(<brace-enclosed initializer list>)'
}

我需要添加什么构造函数才能工作?我曾尝试使用std::initializer_list的构造函数,但到目前为止没有成功。

只需添加一个采用两个无符号int的非显式构造函数,该构造函数使用参数初始化成员。

Size(unsigned int width, unsigned int height) : width(width), height(height) {}