3

假设我有这个结构:

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" };

它隐式调用正确的构造函数(在这种情况下是第一个)。

这有可能吗?

4

1 回答 1

8

您快到了。 MyStruct x = { 1, "string" };称为复制列表初始化。它将尝试使用从braced-init-listMyStruct提供的参数从可用的构造函数构造一个

您的问题是您的构造函数需要一段char*时间"string"是 aconst char[N]可以衰减到 a const char*,而不是 a 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为 astd::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() {}
};
于 2017-08-09T17:38:16.710 回答