如何通过头文件中的函数初始化 const int 数组?

How to initialize a const int array by a function in a header file?

本文关键字:const 初始化 int 数组 函数 何通过 文件      更新时间:2023-10-16

我可以轻松地在头文件中声明和初始化常量数组成员,如下所示:

class MyClass {
public:
const int arr[4] = {1, 2, 3, 4};
}

但是当数据由函数定义时,我无法在标头中初始化它:

#include <cmath>
#define BASE 2
class MyClass {
public:
const int arr[4];
for (i=0;i<4;i++) {
arr[i] = pow(BASE, i);
}
}

当我尝试在.cpp文件中的类构造函数中初始化数组时,我得到了明显的uninitialized member with 'const' type错误,因为数组应该已经初始化了。

如何使用预处理器宏和 cmath 函数初始化头文件中的const int数组?

可以使用BOOST_PP_REPEAT,如果你的数组最多可以有 256 个元素(如果你坚持使用 MSVC(,则更少(。像这样:

#define my_elem(z, n, data) pow(BASE, n)
const int data[4] = {BOOST_PP_REPEAT(4, my_elem, "ignored - extra data not needed")};

但是你真的应该问问自己为什么需要一个非staticconst的成员变量,因为这几乎从来都不是一件有用的事情,并且对程序可以做的事情施加了重大限制(例如,它删除了赋值运算符(。

你可以做这样的事情(如果数组不是太长(:

#include <iostream>
#include <cmath>
#include <functional>
constexpr int BASE = 2;
class A {
public:
A(std::function<int(int)> f);
const int arr[4];
};
A::A(std::function<int(int)> f) :
arr{ f(1),f(2), f(3), f(4) }
{
}
int main() {
auto f = [](int i) { return pow(BASE, i); };
A a(f);
for (const auto val : a.arr) {
std::cout << val << std::endl;
}
return 0;
}
相关文章: