使用 class static const 整数初始化二维数组
Initializing a two dimensional array with class static const integers
我将一个三维数组声明为 class 成员,使用 static const class 成员作为前两个边界:
class A
{
static const uint8_t screenWidth = 256;
static const uint8_t screenHeight = 240;
uint8_t buffer[screenHeight][screenWidth ][3];
}
在 Visual Studio 2019 年我得到以下(奇怪?)错误:
Error (active) E0098 an array may not have elements of this type
如果我求助于 "enum hack" 以声明 class-本地编译时整数常量,它会起作用:
class A
{
enum { SH = 240, SW = 256};
uint8_t buffer[SH][SW][3];
}
前一个示例不应该是 C++11 兼容代码吗? (我猜 Visual Studio 2019 编译器是)。
我认为 uint8_t
类型的对象不能包含值 256。:)
为什么不直接使用类型 size_t
而不是类型 uint8_t
?
static const size_t screenWidth = 256;
static const size_t screenHeight = 240;
您遇到的问题是,在声明中:
static const uint8_t screenWidth = 256;
值 256
对于 uint8_t
类型无效(范围是 0 到 255),它 'rolls over' 给出 actual zero 的值 - 对于数组维度无效。
使您的维度 'constants' 类型更大,您的代码将起作用:
class A {
static const uint16_t screenWidth = 256;
static const uint16_t screenHeight = 240;
uint8_t buffer[screenHeight][screenWidth][3];
};
您的问题与 uint8_t
有关
static const uint8_t screenWidth = 256;//effectively 0
溢出正好是一个大圆零。参见 integer-overflow。
要修复,切换到例如。 size_t
(也更适合尺码)
我将一个三维数组声明为 class 成员,使用 static const class 成员作为前两个边界:
class A
{
static const uint8_t screenWidth = 256;
static const uint8_t screenHeight = 240;
uint8_t buffer[screenHeight][screenWidth ][3];
}
在 Visual Studio 2019 年我得到以下(奇怪?)错误:
Error (active) E0098 an array may not have elements of this type
如果我求助于 "enum hack" 以声明 class-本地编译时整数常量,它会起作用:
class A
{
enum { SH = 240, SW = 256};
uint8_t buffer[SH][SW][3];
}
前一个示例不应该是 C++11 兼容代码吗? (我猜 Visual Studio 2019 编译器是)。
我认为 uint8_t
类型的对象不能包含值 256。:)
为什么不直接使用类型 size_t
而不是类型 uint8_t
?
static const size_t screenWidth = 256;
static const size_t screenHeight = 240;
您遇到的问题是,在声明中:
static const uint8_t screenWidth = 256;
值 256
对于 uint8_t
类型无效(范围是 0 到 255),它 'rolls over' 给出 actual zero 的值 - 对于数组维度无效。
使您的维度 'constants' 类型更大,您的代码将起作用:
class A {
static const uint16_t screenWidth = 256;
static const uint16_t screenHeight = 240;
uint8_t buffer[screenHeight][screenWidth][3];
};
您的问题与 uint8_t
static const uint8_t screenWidth = 256;//effectively 0
溢出正好是一个大圆零。参见 integer-overflow。
要修复,切换到例如。 size_t
(也更适合尺码)