代码之家  ›  专栏  ›  技术社区  ›  Fylax

自定义大括号初始值设定项

  •  3
  • Fylax  · 技术社区  · 7 年前

    假设我有一个结构:

    struct MyStruct {
        int field1;
        char *field2;
        MyStruct(int a, char* b): field2(b) {
            field1 = doStuff(a);
        }
        MyStruct(int a): MyStruct(a, nullptr) {}
        ~MyStruct();
    }
    

    据我所知,这不是一个聚合,因为我有一些构造函数。

    我想要实现的是使用

    MyStruct x = { 1, "string" };
    

    隐式调用适当的构造函数(本例中的第一个构造函数)。

    这有可能吗?

    1 回复  |  直到 7 年前
        1
  •  8
  •   NathanOliver    7 年前

    你就快到了。 MyStruct x = { 1, "string" }; 被称为 复制列表初始化 MyStruct 带括号的初始化列表

    你的问题是你的构造函数需要一个 char* 虽然 "string" const char[N] 它可以衰变为 const char* .所以让事情改变

    struct MyStruct {
        int field1;
       const char* field2;
        MyStruct(int a, const char* b): field2(b) {
            field1 = a;
        }
        MyStruct(int a): MyStruct(a, nullptr) {}
        ~MyStruct() {}
    };
    

    然后

    MyStruct x = { 1, "string" };
    

    field2 成为一名 std::string

    struct MyStruct {
        int field1;
        std::string field2;
        MyStruct(int a, const std::string& b): field1(a), field2(b) {}
        MyStruct(int a): MyStruct(a, "") {}
        ~MyStruct() {}
    };