如何通过头文件中的函数初始化 const int 数组?
How to initialize a const int array by a function in a header file?
我可以轻松地在头文件中声明和初始化常量数组成员,如下所示:
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")};
但是你真的应该问问自己为什么需要一个非static
但const
的成员变量,因为这几乎从来都不是一件有用的事情,并且对程序可以做的事情施加了重大限制(例如,它删除了赋值运算符(。
你可以做这样的事情(如果数组不是太长(:
#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;
}
相关文章:
- 如何在旧c++中初始化const-std向量
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 为什么通过指针编译时不能分配 const 初始化
- 类型为 "Bucket&"(未限定的 const 限定)的引用不能使用 "SortedList." 类型的值进行初始化 如何修复此错误?
- 初始化类中的静态 const 数组 - C++
- 无法使用类型 'const char *' 的左值初始化类型 'char *' 的成员子对象
- 我可以初始化 const 实例,以便我可以将其用作 const 来初始化数组吗?
- "const wchar_t *" 类型的值不能用于初始化类型 "const PWSTR" 的实体
- Visual Studio C++:不能使用类型为 "const wchar_t *" 的值来初始化类型为 "TCHAR *" 的实体
- 使用 const char* 初始化 const ref 字符串成员时幕后会发生什么
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 如何使用 C++ 中的原语初始化类(如 std::字符串从 const char* 初始化)
- 如何使用函数的输出初始化 const 数组结构字段?
- 有效地初始化 const std::vector 类成员
- 使用 extern const 初始化函数
- C++ 非整型模板 Const 初始化 预期在类名之前使用初始化声明符
- 使用const初始化constexpr,--int vs float
- 错误的静态const初始化,编译和工作
- Visual Studio 2013 CTP是否支持非整型的类内静态const初始化式?