【发布时间】:2017-01-09 10:03:28
【问题描述】:
当我将 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;
【问题讨论】:
-
您没有将数组传递给构造函数(无论您怎么想)。您正在传递一个指向数组第一个元素的指针。
-
我怎么没找到那个页面!谢谢你,这就是我需要的。是的,我想我会删除这个问题。感谢您的帮助马丁邦纳! (如果我现在考虑是否允许我删除它,idk)
-
我认为 you 可以将其作为副本关闭。 SO 关于重复的政策是关闭它们,但不删除它们(以便其他人有更好的机会找到它们)。
标签: c++ arrays constructor