-1

我正在使用 C++ Builder,并且在将 const int 变量设置为向量的大小方面得到了一些帮助。

这是我的有效代码,只是为了向您展示什么有效:

vector<appointment> appointmentVector = calCalendar.getAllAppointments();

const int sizeOfArray = 5;
unsigned int arr[sizeOfArray];

如果我将代码修改为以下内容:

vector<appointment> appointmentVector = calCalendar.getAllAppointments();

const int sizeOfArray = appointmentVector.size();
unsigned int arr[sizeOfArray];

我收到以下错误:

[BCC32 错误] Assessment2.cpp(357): E2313 需要常量表达式

我可以帮忙吗?

更新

我在问这个问题时遇到以下代码问题:

unsigned int arr[2] = {1,8};
unsigned int days;
TMonthCalendar->BoldDays(arr, 1, days);
MonthBoldInfo = days;

BoldDays 方法需要一个无符号整数数组,但我只知道运行时的值。你能告诉我如何找到解决这个问题的方法吗?

4

3 回答 3

0

静态数组需要编译时常量,因此第二个代码永远不会编译,因为数组的大小在编译时是未知的。如果将 arr 声明为向量或动态数组会更好。

这是基本的 C++ 问题,建议您阅读 C++ 初学者书籍。

于 2012-10-11T04:52:56.923 回答
0

您的代码的问题是您将非常量表达式结果值(在运行时评估的值)分配给 const 变量,其值需要是从常量表达式(在编译时评估的值)或文字生成的值.

要解决此问题,您不应使用constin sizeOfArray

int sizeOfArray = appointmentVector.size();

此外,一旦您解决了上述问题,您应该创建一个动态分配的数组

unsigned int* arr = new unsigned int[sizeOfArray];

动态分配的数组允许您创建元素数量可以来自运行时值的数组。

于 2012-10-11T04:55:06.933 回答
0

常量表达式是编译器可以计算出值的表达式。在 C++ 中,数组的大小是其类型的一部分,并且必须作为常量表达式给出。如果编译器不能确定一个表达式有什么值,你就不能用它作为数组类型的大小。您可以做的是在堆上分配一个“数组”并使用指向其第一个元素的指针,就像您通常使用数组名称一样。

于 2012-10-11T04:56:16.663 回答