在成员函数之间传递const变量为数组的索引

Passing const variable between member functions to be index of array

本文关键字:变量 数组 索引 const 成员 函数 之间      更新时间:2023-10-16

我试图解决这个问题,但是我不能。我有一个类定义,我希望成员函数(SIZ(将常数值返回到另一个成员函数(ABC(。该值在该功能中的数组声明中用作最大索引。但这似乎不起作用。这是一个简化的版本:

class bin {
    constexpr int siz();
public:
    void abc();
};
constexpr int bin::siz() {
    const int sizz = sizeof(int) * 8;
}
void bin::abc() {
    char arr[siz()];   // compiler: this expression didn't evaluate as constant (¿?)
};

但是,其他非常相似的代码(但使用简单函数(确实编译了...

constexpr int siz() {
    const int sizz = sizeof(int) * 8;
    return sizz;
}
int main() {
    char arr[siz()];
    return 0;
}

我不完全确定,但是我认为问题是在bin::abc中,该对象可以在运行时是任何东西。因此,bin::siz()无法在编译时进行评估。

以下工作正常

int main()
{
   bin b;
   char arr[b.siz()];
}

bin更改为:

class bin {
public:
    constexpr int siz();
};
constexpr int bin::siz() {
    return sizeof(int) * 8;
}

如果siz不取决于对象的状态,例如在您发布的代码中,我建议将其作为static成员函数。

以下对我有效。

class bin {
  public:
    static constexpr int siz();
    void abc() const;
};
constexpr int bin::siz() {
  return sizeof(int) * 8;
}
void bin::abc() const {
  char arr[siz()];
}
int main()
{
  bin b;
  char arr[b.siz()];
}