【发布时间】:2023-02-11 01:46:46
【问题描述】:
看来我根本不了解大括号初始化列表。为什么以下代码针对 operator=() (entity e) 而不是针对构造函数 (entity f) 进行编译?
#include <cstdio>
#include <utility>
#include <string_view>
struct entity
{
using keyval_t = std::pair<std::string_view, std::string_view>;
entity() = default;
entity(keyval_t keyval) {
printf("our special ctor called!\n");
}
auto operator=(keyval_t keyval) {
printf("our special operator called!\n");
}
};
int main()
{
entity e;
// entity f = { "Hello", "World"}; <-- doesn't work??
e = { "Hello", "World" };
}
奖金问题: 如何使它在这两种情况下都起作用?
【问题讨论】:
-
仅供参考:
entity f = { { "Hello", "World" } };有效。 (你在第二个构造函数中的参数是std::pair。)Demo -
@Scheff'sCat 好的,但为什么在 operator=() 情况下它会这样工作?有什么不同?
标签: c++ std-pair list-initialization stdinitializerlist braced-init-list