我正在尝试使用我的常量字段作为其维度来定义多维数组,但我收到一个编译错误,指出该表达式不是常量。有没有其他方法可以使用构造函数初始化列表中定义的常量字段作为数组维度?
针对大多数英语人士的翻译:
class FunctionWave2D : public DisallowedDomainPoints
{
protected:
double th;
double l; a
double d, dd;
const int number_sqrt; //here's the constant
double **second_derivatives;
protected:
bool elasticTenstionOnly;
public:
FunctionWave2D(int number, double elasticModulus, double dampingFactor, double oscillationDampingFactor, double length)
:DisallowedDomainPoints(number * LAYER_COUNT),
th(elasticModulus), d(dampingFactor), dd(oscillationDampingFactor),
elasticTensionOnly(false),
l(length/(sqrt(number)-1)),
number_sqrt(sqrt(number))
{
second_derivatives = new double[number_sqrt][number_sqrt][LAYER_COUNT];
//(...)
最佳答案
在 C++ 中,术语“常量表达式”特指其值在编译时已知的表达式。它与 const
变量不同。比如137
是一个常量表达式,但是在这段代码中:
int function(int x) {
const int k = x;
}
k
的值不是常量表达式,因为它的值无法在编译时确定。
在你的例子中,你有一个数据成员声明为
const int ilosc_sqrt; //here's the constant
即使它被标记为 const
,它的值在编译时也是未知的。它在初始化列表中被初始化为
ilosc_sqrt(sqrt(ilosc))
在程序实际运行之前无法确定此值,因此会出现错误。 (请注意,新的 C++11 constexpr
关键字旨在使常量表达式在源代码中更容易识别,并使进行更高级的编译时计算成为可能有常量。)
要解决此问题,您需要将初始化分成更小的步骤:
drugie_pochodne = new double**[ilosc_sqrt];
for (int i = 0; i < ilosc_sqrt; i++) {
drugie_pochodne[i] = new double*[ilosc_sqrt];
for (int j = 0; j < ilosc_sqrt; j++) {
drugie_pochodne[j] = new double[ILOSC_WARSTW];
}
}
或者使用像 Boost.MultiArray 这样的库,它支持更清晰的初始化语法。
希望这对您有所帮助!
关于c++ - 当字段为 const 时获取 'Non-constant expression as array bound',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17198614/