【问题标题】:from '<brace-enclosed initializer list>' to X: understanding list initialization in constructors从 \'<brace-enclosed initializer list>\' 到 X:理解构造函数中的列表初始化
【发布时间】:2023-02-11 01:46:46
【问题描述】:

看来我根本不了解大括号初始化列表。为什么以下代码针对 operator=() (entity e) 而不是针对构造函数 (entity f) 进行编译?

Demo

#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


【解决方案1】:

std::pair 有两个成员变量,因此应该传递两个给定值。

这有效

entity f = { {"Hello", "World"} };
             ^________________^  
                 keyval_t
           ^____________________^
          entity::entity(keyval_t)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多