gpt4 book ai didi

c++ - 在 C++03 中初始化 const 成员的正确方法

转载 作者:行者123 更新时间:2023-11-30 05:13:50 24 4
gpt4 key购买 nike

我需要为遗留环境编写一些 C++03 代码。以下代码编译但编译器 (g++ (SUSE Linux) 6.3.1 20170202 [gcc-6-branch revision 245119]) 提示。

代码:

typedef unsigned char Key[100];

class A {
public:
const Key key1 {0x1};
const Key key2;

A(): key2({0x1}) {};
};

int main() {
A a;
return 0;
}

编译器输出:

test.cpp:6:24: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
const Key key1 {0x1};
^
test.cpp:6:20: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11
const Key key1 {0x1};
^
test.cpp:6:24: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11
const Key key1 {0x1};
^
test.cpp: In constructor ‘A::A()’:
test.cpp:10:15: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11
A(): key2({0x1}) {};
^
test.cpp:10:20: warning: list-initializer for non-class type must not be parenthesized
A(): key2({0x1}) {};

那么初始化 const 数组成员的正确方法是什么(即符合 C++03)?

最佳答案

C++11 引入了在初始化列表中初始化数组成员的能力。需要此功能来将数组元素初始化为非零的特定值。由于无法复制数组,因此提供用于复制的初始化数组也不起作用。

但是, 的工作是用 struct 包装数组并通过复制这样的 来初始化 const 成员结构。例如:

template <int Size>
struct array {
unsigned char value[Size];
};
typedef array<100> Key;
class A {
Key const key1;
Key const key2;
static Key make_key() {
Key rc = Key();
rc.value[0] = 0x1;
// whatever else
return rc;
}
public:
A(): key1(make_key()), key2(make_key()) {}
};

make_key() 中的初始化仅类似于示例中的初始化(第一个元素初始化为 0x1,所有其他元素初始化为零)。显然,它可以做任何其他需要的事情,可能基于从构造函数转发的参数。

关于c++ - 在 C++03 中初始化 const 成员的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43728712/

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