1

所以我遇到了一个问题,无法创建一个可变大小的新数组(变量声明为const int

这是代码

#include <iostream>
#include <string>

int newArraySize;

int main ()
{
   std::cin >> newArraySize;

   int const fin = newArraySize;

   int deduped[fin]; // Here is the error
}

我得到的错误是

错误:表达式必须具有常量值

我尝试将其转换为常量但仍然没有运气(同样的错误)

int const fin = const_cast<int const&>(newArraySize);
int deduped[fin]; 
4

2 回答 2

3

C++ 有(令人困惑的)两种形式的const. 你fin是一种类型,但一种类型是数组大小所必需的。另一种类型是新调用constexpr的,以前是“编译时常量”。你看,所有数组都必须是 C++ 编译器已知的固定大小。所以仅仅创建一个变量是不够的const,编译器还必须能够计算出这个。因此,要么newArraySize必须是编译时常量表达式,要么更可能的是,您必须使用动态数组,最好由std::vector.

std::vector<int> deduped(newArraySize);

如果您不能使用 a vector,还有其他(更糟糕的)选项:使用andstd::unique_ptr<int[]>自己管理动态内存,或者制作一个具有编译时常数最大大小(1000)的本地数组,并分别跟踪有多少元素你实际上正在使用。int* deduped=new[newArraySize]();delete deduped;

于 2013-03-03T20:04:59.527 回答
-1

newArraySize未声明为 const。这样做,它会工作。

于 2013-03-03T19:57:37.247 回答