【问题标题】:How to initialize a const int array by a function in a header file?如何通过头文件中的函数初始化 const int 数组?
【发布时间】:2017-07-30 22:18:47
【问题描述】:

我可以像这样在头文件中轻松声明和初始化一个常量数组成员:

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' typeerror,因为数组应该已经被初始化了。

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

【问题讨论】:

  • 函数在哪里?
  • 在这样的函数之外的类定义中不能有循环。
  • @uzumaki -- 此部分适用于 cmets,StoryTeller 发表了评论。
  • 如果你对试图让你头疼的人无礼,你应该维护这样的代码。

标签: c++ arrays macros initialization preprocessor


【解决方案1】:

可以使用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 的成员变量,因为这几乎从来都不是有用的事情,并且有很大的限制关于您的程序可以做什么(例如,它删除了赋值运算符)。

【讨论】:

    【解决方案2】:

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

    #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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 2012-11-10
      • 2016-08-14
      相关资源
      最近更新 更多