【发布时间】:2015-10-29 20:52:18
【问题描述】:
在开始之前,我正在使用 VS2015 C++ 语言编译程序。当我尝试确定两个常量数组的大小时,问题是编译错误。问题涉及的类:
头文件:
#ifndef RACE_H_
#define RACE_H_
class Race
{
private:
static const int PILOT_POINTS[];
static const double TEAM_AWARDS[];
}
#endif
源文件:
#include "Race.h"
const int PILOT_POINTS[] = { 25, 18, 15, 12, 10, 8, 6, 4, 2, 1 };
const double TEAM_AWARDS[] = { 100000, 75000, 50000, 25000, 15000, 10000 };
部分错误:
sizeof(TEAM_AWARDS) / sizeof(TEAM_AWARDS[0]))
sizeof(PILOT_POINTS) / sizeof(PILOT_POINTS[0]))
编译器说:
错误 2070 const int[] 操作数 sizeof 无效。
不允许使用不完整的类型。
错误 2070 const double[] 操作数 sizeof 无效。
不允许使用不完整的类型。
我可以使用 extern 来解决这个问题吗?如果是,我应该如何使用它?
【问题讨论】:
-
有什么理由不使用
const std::vector<int> PILOT_POINTS?然后你可以使用PILOT_POINTS.size() -
sizeof是运算符,而不是函数。 -
另外
const int PILOT_POINTS[] = { 25, 18, 15, 12, 10, 8, 6, 4, 2, 1 };不是从类中初始化数组,而是创建一个全局数组。您需要将其更改为const int Race::PILOT_POINTS[] = { 25, 18, 15, 12, 10, 8, 6, 4, 2, 1 }; -
@CoryKramer:
std::vector::size()不是编译时常量。sizeof是。如果您将其用作模板非类型参数、初始化枚举或用作另一个数组的维度,则非常重要。 -
@BenVoigt 好点,在这种情况下他们可以使用
std::array,因为std::array::size是编译时间常数,即constexpr
标签: c++ arrays constants sizeof