有没有办法初始化一个不涉及编写构造函数的新结构变量?

问题描述 投票:6回答:3

我认为我模糊地回忆起一个较新的c ++标准(可能是它的c ++ 11,或者14?〜?17 ??)允许你初始化一个结构,你可以定义一个结构然后在没有它的情况下初始化它必须编写构造函数。

Ef。:

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
3个回答
4
投票

“没有构造函数的初始化”被称为聚合初始化,它从第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

4
投票

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

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

或者干脆

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

1
投票

您还可以默认初始化:

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"));
© www.soinside.com 2019 - 2024. All rights reserved.