我是一個JavaScript程序員,他試圖通過將我的JavaScript類移植到C++來學習C++。我很快發現C++數組中的數組與JavaScript中的數組非常不同。在構造函數中初始化數組
我班的成員有數組屬性。我無法在構造函數中初始化數組。這是我的代碼。
class Name {
private:
unsigned int array[];
public:
unsigned int getArray();
Name(unsigned int);
}
//I'm defining everything outside the class because I'm told that's good practice
unsigned int Name::getArray() {
return this->array;
}
//this is the problem
Name::Name(unsigned int length) {
this->array = new unsigned int [length];
}
我沒有線索如何解決最後一部分。我一直在亂搞它很多年。似乎沒有任何工作。其餘的代碼很好,我只是得到1構造函數的錯誤。
我使用g ++編譯。
如果您想要一個大小在運行時決定的數組,請改用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。 –
也看看'std :: array'。見[這裏](http://en.cppreference.com/w/cpp/container/array)。 – skypjack
問題:1.'new'返回一個指針,而不是一個數組。 2.你不能分配給一個數組(你正混淆賦值和初始化)。 –