繁体   English   中英

C++ 预期的常量表达式

[英]C++ expected constant expression

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

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

float x[size][2];

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

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

或者使用新的

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

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

如果您没有可用的 C++11,则可以使用boost::array而不是std::array

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

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

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

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

如果需要,您还可以使用std::pair<float, float>的向量

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM