C++ 预期的常量表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2448380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:31:33  来源:igfitidea点击:

C++ expected constant expression

c++arraysconstant-expression

提问by n0ob

#include <iostream>
#include <fstream>
#include <cmath>
#include <math.h>
#include <iomanip>
using std::ifstream;
using namespace std;

int main (void)

{
int count=0;
float sum=0;
float maximum=-1000000;
float sumOfX;
float sumOfY;
int size;
int negativeY=0;
int positiveX=0;
int negativeX=0;
ifstream points; //the points to be imported from file
//points.open( "data.dat");
//points>>size;
//cout<<size<<endl;

size=100;
float x[size][2];
while (count<size) {



points>>(x[count][0]);
//cout<<"x= "<<(x[count][0])<<"  ";//read in x value
points>>(x[count][1]);
//cout<<"y= "<<(x[count][1])<<endl;//read in y value


count++;
}

This program is giving me expected constant expression error on the line where I declare float x[size][2]. Why?

这个程序在我声明 float x[size][2] 的那一行给了我预期的常量表达式错误。为什么?

回答by Johannes Schaub - litb

float x[size][2];

That doesn't work because declared arrays can't have runtime sizes. Try a vector:

这不起作用,因为声明的数组不能有运行时大小。尝试向量:

std::vector< std::array<float, 2> > x(size);

Or use new

或者使用新的

// identity<float[2]>::type *px = new float[size][2];
float (*px)[2] = new float[size][2];

// ... use and then delete
delete[] px;


If you don't have C++11 available, you can use boost::arrayinstead of std::array.

如果您没有可用的 C++11,则可以使用boost::array代替std::array.

If you don't have boost available, make your own array type you can stick into vector

如果您没有可用的提升,请制作您自己的数组类型,您可以坚持使用矢量

template<typename T, size_t N>
struct array {
  T data[N];
  T &operator[](ptrdiff_t i) { return data[i]; }
  T const &operator[](ptrdiff_t i) const { return data[i]; }
};

For easing the syntax of new, you can use an identitytemplate which effectively is an in-place typedef (also available in boost)

为了简化 的语法new,您可以使用一个identity模板,它实际上是一个就地 typedef(也可以在 中使用boost

template<typename T> 
struct identity {
  typedef T type;
};


If you want, you can also use a vector of std::pair<float, float>

如果你愿意,你也可以使用一个向量 std::pair<float, float>

std::vector< std::pair<float, float> > x(size);
// syntax: x[i].first, x[i].second

回答by Justin Ethier

The array will be allocated at compile time, and since sizeis not a constant, the compiler cannot accurately determine its value.

该数组将在编译时分配,由于size不是常量,编译器无法准确确定其值。

回答by dirkgently

You cannot have variable length arrays (as they are called in C99) in C++. You need to use dynamically allocated arrays (if the size varies) or a static integral constant expression for size.

在 C++ 中不能有可变长度数组(因为它们在 C99 中被调用)。您需要使用动态分配的数组(如果大小变化)或大小的静态整数常量表达式。

回答by JSB????

The line float x[size][2]won't work, because arrays have to be allocated at compile time (with a few compiler-specific exceptions). If you want to be able to easily change the size of the array xat compiletime, you can do this:

该行将float x[size][2]不起作用,因为必须在编译时分配数组(有一些特定于编译器的例外)。如果您希望能够x编译时轻松更改数组的大小,您可以这样做:

 #define SIZE 100
 float x[SIZE][2];

If you really want to allocate the array based on information you only have at runtime, you need to allocate the array dynamically with mallocor new.

如果您真的想根据只有在运行时拥有的信息来分配数组,则需要使用malloc或动态分配数组new

回答by mszaro

You haven't assigned any value to size; thus the compiler cannot allocate the memory for the array. (An array of null size? What?)

你没有给 size 赋值;因此编译器无法为数组分配内存。(空大小的数组?什么?)

Additionally, you'd need to make SIZE a constant, and not a variable.

此外,您需要将 SIZE 设为常量,而不是变量。

EDIT:Unfortunately, this response no longer makes sense since the poster has changed their question.

编辑:不幸的是,由于海报已经改变了他们的问题,所以这个回答不再有意义。

回答by JaredPar

It is a restriction of the language. Array sizes must be constant expressions. Here's a partial jsutification from cplusplus.com

这是语言的限制。数组大小必须是常量表达式。这是来自 cplusplus.com 的部分 jsutification

NOTE: The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials.

注意:括号 [] 中的元素字段表示数组将要保存的元素数,必须是一个常量值,因为数组是非动态内存块,其大小必须在执行前确定。为了创建具有可变长度动态内存的数组,需要在这些教程的后面进行解释。

回答by UncleBens

The size of an automatic array must be a compile-time constant.

自动数组的大小必须是编译时常量。

 const int size = 100;
 float x[size][2];

If the size weren't known at compile-time (e.g entered by the user, determined from the contents of the file), you'd need to use dynamic allocation, for example:

如果在编译时不知道大小(例如,由用户输入,根据文件内容确定),则需要使用动态分配,例如:

std::vector<std::pair<float, float> > x(somesize);

(Instead of a pair, a dedicated Point struct/class would make perfect sense.)

(而不是一对,专用的 Point 结构/类将非常有意义。)

回答by Lightness Races in Orbit

Because it expected a constant expression!

因为它期望一个常量表达式!

Array dimensions in C (ignoring C99's VLAs) and C++ must be quantities known at compile-time. That doesn't mean just labelled with const: they haveto be hard-coded into the program.

C(忽略 C99 的 VLA)和 C++ 中的数组维度必须是编译时已知的数量。这并不意味着只是标记为const:它们必须被硬编码到程序中。

Use dynamic allocation or std::vector(which is a wrapper around dynamic array allocation) to determine array sizes at run-time.

使用动态分配或std::vector(它是动态数组分配的包装器)在运行时确定数组大小。