简体   繁体   English

为什么不能将一个数组分配给另一个数组?

[英]Why can't I assign an array to another?

I can't seem to wrap my head around the reason the following code won't compile. 我似乎无法将以下代码无法编译的原因束之高阁。

In my header file I declared an array as a static class member: 在我的头文件中,我将数组声明为静态类成员:

class foo {
private:
#define SIZE 50
static char array[SIZE];
// further code goes here
}

In the implementation, I have to initialize the array. 在实现中,我必须初始化数组。

char foo::array[SIZE] = new[] char[SIZE];

This yields me an error everytime - the compiler says: 每次都会给我一个错误-编译器说:

cannot convert from 'char *' to 'char [50]' 无法从“字符*”转换为“字符[50]”

Why does the compiler interpret new[] char[SIZE] as char* ? 为什么编译器将new[] char[SIZE]char*

  1. There's no such thing as new [] . 没有new []这样的东西。 You need to remove the [] . 您需要删除[]
  2. Because ::operator new returns a pointer, not an array. 因为::operator new返回一个指针,而不是数组。 Pointers are not arrays, and trying to treat the two interchangeably will result in pain. 指针不是数组,尝试将它们互换使用会导致痛苦。 Just because arrays will decay into pointers doesn't mean that arrays are pointers. 仅仅因为数组将衰减为指针并不意味着数组就是指针。
  3. foo::array[SIZE] is already static -- there's no need to allocate storage for it in any case. foo::array[SIZE]已经是static -在任何情况下都不需要为其分配存储空间。
  4. This looks like you're coming from a Java or C# background, where arrays are reference types. 看起来您来自Java或C#背景,其中数组是引用类型。 Arrays are not reference types in C++. 数组不是C ++中的引用类型。 When you declare the array the storage for it is implicit. 声明数组时,其存储是隐式的。 In your case the storage is going to be where all the other static s are; 在您的情况下,存储将位于所有其他static的位置; if the array was just written that way without static in a function then it would be allocated on the stack. 如果数组只是在函数中没有static情况下编写的,那么它将在堆栈上分配。

In C++ array is almost like constant pointer ( char * const , not char const * ). 在C ++中,数组几乎就像常量指针( char * const ,而不是char const * )。 If you assign pointer to another pointer you just copy the address, not the value. 如果将指针分配给另一个指针,则只需复制地址,而不是值。

As Billy said in your case you don't need to allocate memory for the array, it's already allocated, because you declared it as static array with fixed length. 正如Billy所说的那样,您不需要为数组分配内存,因为已经将其声明为固定长度的静态数组,所以已经分配了内存。 You use operator new if you want to create object on heap or array with length known in runtime. 如果要在运行时在堆或数组上创建长度已知的对象,请使用new运算符。 You can to this like this: 您可以这样:

class A{
public:
    A(int s): array_(new char[s]), length_(s) {}
    ~A() { delete [] array_; }
private:
    char * const array_;
    int length_;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM