gpt4 book ai didi

c++ - 声明后初始化 boost::array

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:23:00 26 4
gpt4 key购买 nike

我们可以使用以下语法初始化 boost 或 std::array:

array<int,5> b = {1, 2, 3, 4, 5};

如果 'b' 是局部变量,这很好。如果'b'是类(class)成员怎么办?

b = {1, 2, 3, 4, 5}; // Error: expected an expression
b = array<int,5>{1, 2, 3, 4, 5}; // Error: type name is not allowed
b = array<int,5>({1, 2, 3, 4, 5}); // Error: expected an expression
b = array<int,5>(1, 2, 3, 4, 5); // Error: no suitable constructor exists to convert from "int" to "array<int, 5>"

你真的必须这样做吗:

array<int,5> c = {1, 2, 3, 4, 5};

b = c;

这看起来有点浪费,因为它创建“c”,初始化它,然后在销毁“c”之前将其复制到 b 中。

最佳答案

您还可以在声明时初始化数据成员:

struct Foo
{
array<int,5> b = {1, 2, 3, 4, 5};
};

或者,你也可以使用构造函数初始化列表

struct Foo
{
Foo() : b{1, 2, 3, 4, 5} {}
array<int,5> b;
};

请注意,您所有涉及 b = X 的语句都不是初始化,它们是赋值

编辑:这种初始化在 C++03 中是不可能的,但是你可以通过调用一个返回合适的初始化数组的函数来实现类似的东西:

boost::array<int, 5> make_array()
{
// trivial example, but you can do more complicated stuff here
boost::array<int, 5> a = {{1, 2, 3, 4, 5}};
return a;
}

然后

Foo() : b(make_array()) {}

关于c++ - 声明后初始化 boost::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23184257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com