C++ 预期的常量表达式 [英] C++ expected constant expression

查看:42
本文介绍了C++ 预期的常量表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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] 的那一行给了我预期的常量表达式错误.为什么?

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

推荐答案

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);

或者使用新的

// 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.

如果您没有可用的提升,请制作您自己的数组类型,您可以将其放入向量中

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

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

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

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

<小时>

如果你愿意,你也可以使用 std::pair

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

这篇关于C++ 预期的常量表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆