【问题标题】:Is there a way to initialise a new struct variable that does not involve writing a constructor?有没有办法初始化一个不涉及编写构造函数的新结构变量?
【发布时间】:2018-11-01 13:00:18
【问题描述】:

我想我隐约记得其中一个较新的 c++ 标准(可能是它的 c++11,或者可能是 14?...17??)允许您初始化一个结构,由此您可以定义一个结构,然后无需编写构造函数即可对其进行初始化。

例如:

struct test
{
    int a;
    int b;
    std::string str;
};

int main()
{
    std::map<int, test> test_map;
    test_map[0] = test(1, 2, "test1"); // This is the line in question
    // Or it might be more like: test_map[0] = test{1, 2, "test1"};
    return 0;
}

我不记得这个特殊初始化的名称(或者它是否存在)!。所以我的问题是:

  • 是否有一些新的机制来实现这一点,而无需在结构“test”中编写构造函数?
  • 如果是这样,它叫什么(所以我可以阅读更多关于它的信息)。

如果这个“功能”不存在,那么请让我摆脱痛苦!可能是我的想象力造成的......

【问题讨论】:

标签: c++ c++11 struct initialization


【解决方案1】:

“没有构造函数的初始化”被称为聚合初始化,从第一天开始它就一直是 C++ 的一部分。不幸的是,有些人可能会说。

在 C++98 中你可以这样写:

std::map<int, test> test_map;
test temp = { 1, 2, "test1" };
test_map[0] = temp;

C++11补充说可以在prvalues中使用聚合初始化,所以不需要声明中间变量(也没有多余的副本):

std::map<int, test> test_map;
test_map[0] = { 1, 2, "test1" };

std::map<int, test> m2 = { {0, {1, 2, "test2"}} };    // and this

【讨论】:

  • 正是我要找的东西(例如和“事物”的名称:)....虽然事实证明我的 MSVC2012 编译器只部分支持 c++11,所以我必须现在使用 C++98 方法:(
【解决方案2】:

你也可以默认初始化:

struct test {
    int a{1};
    int b{2};
    std::string str{"test1"};
};

或者没有赋值的构造:

std::map<int, test> test_map{ 
    {0, {1, 2, "test1"}}
};

或者不复制就插入:

test_map.emplace(std::piecewise_construct,
    std::forward_as_tuple(0),
    std::forward_as_tuple(1, 2, "test1"));

【讨论】:

  • 这不是我要问的,但非常有趣:) 第一个例子对我来说也是全新的。我用我的 MSVS2012 编译器试了一下,它不喜欢它。这是 >= c++11 的新功能吗?
  • 啊,好的-谢谢,这解释了原因:) ...好消息是我们将很快获得 MSVS2017 v,所以我会尝试一下:p
【解决方案3】:

没有构造函数,你可以这样做

test_map[0] = test{ 1, 2, "test1" };

或者干脆

test_map[0] = { 1, 2, "test1" };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多