将数组传递给构造函数会产生一个大小为1的数组?

时间:2017-01-09 10:03:28

标签: c++ arrays constructor

当我将nums传递给主文件中声明的第三个变量时,会出现问题。

当我将主文件中的整数数组传递给构造函数时,构造函数只接收指向第一个数组元素的指针。我如何传递数组,以便将数组的地址传递给我的构造函数,以便将所有内容复制到我的treeArray类的成员指针中?

treeArray.h

class treeArray
{
private:
int arraySize;
int* arr;

public:
//Constructors
treeArray();
treeArray(int capacity);
treeArray(treeArray& passed); //copy constructor
treeArray(int passed[]);

//Destructor
~treeArray();

//Get Functions
int getArrCap();

//Display functions
bool displayArray();
};

treeArray.cpp:

//copy an array of ints to a treeArray
treeArray::treeArray(int passed[])
{
//get the size of the array passed and assign it to member array size
this->arraySize = sizeof(passed)/sizeof(passed[0]);

this->arr = new int[this->arraySize];

for(int i = 0; i < this->arraySize; i++)
    this->arr[i] = passed[i];
}

主:

int nums[] = {7, 9, 10, 15};

treeArray first;
treeArray second(5);
treeArray third(nums);
treeArray fourth(third);


cout << "Arrays: " << endl << "#1: ";
first.displayArray();
cout << endl << "#2: ";
second.displayArray();
cout << endl << "#3: ";
third.displayArray();
cout << endl << "#4: ";
fourth.displayArray();
cout << endl << endl;

2 个答案:

答案 0 :(得分:0)

treeArray::treeArray(int passed[])
{
    ...
    this->arraySize = sizeof(passed)/sizeof(passed[0]);

}

注意sizeof(passed)sizeof(pointer-to-int)(因为此处数组衰减到指针),因此sizeof(passed)/sizeof(passed[0])通常只是1,因为您注意到(因为指针通常是相同的)大小int

如果只将数组传递给函数,则无法计算出数组大小。通常需要一个额外的参数(例如array_size)与数组本身一起传递。

答案 1 :(得分:0)

treeArray(int passed[]);相当于treeArray(int* passed);

要获得尺寸,您应该使用

template<std::size_t N>
treeArray(int (&passed)[N]);

treeArray(int passed[], std::size_t size);