我似乎无法理解以下代码无法编译的原因.
在我的头文件中,我将数组声明为静态类成员:
class foo {
private:
#define SIZE 50
static char array[SIZE];
// further code goes here
}
Run Code Online (Sandbox Code Playgroud)
在实现中,我必须初始化数组.
char foo::array[SIZE] = new[] char[SIZE];
Run Code Online (Sandbox Code Playgroud)
每次都会产生错误 - 编译器说:
无法从'char*'转换为'char [50]'
为什么编译器解释new[] char[SIZE]为char*?
new [].你需要删除[].::operator new返回一个指针,而不是一个数组.指针不是数组,并试图互换地处理这两个将导致痛苦.仅仅因为数组会衰减成指针并不意味着数组是指针.foo::array[SIZE]已经static- 在任何情况下都没有必要为它分配存储空间.static的存储; 如果数组只是static在没有函数的情况下以这种方式写入,那么它将被分配在堆栈上.