簡體   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