我正在练习,以便更好地理解动态数组并在类中使用它们。然而,我正在努力在类中调用我的函数。我没有问题与我的int大小变量,但我的int myArray变量给我的问题。我得到错误"期望一个成员名"。当我试图在主函数中调用void函数时。在这种情况下不允许使用数组吗?
#include <iostream>
using namespace std;
class myClass
{
public:
int size;
int* myArray = new int[size];
void storeData(int& size, int (&myArray)[]);
void printData(int& size, int(&myArray)[]);
};
void myClass::storeData(int& size, int(&myArray)[])
// Stores array data.
{
cout << "Enter Size of the array: ";
cin >> size;
// User determines array size.
for (int x = 0; x < size; x++)
{
cout << "Array[" << x << "]: ";
cin >> myArray[x];
// User determines array values.
cout << endl;
}
}
void myClass::printData(int &size, int(&myArray)[])
// Displays values of the array.
{
cout << "Value of the arrays are: ";
for (int x = 0; x < size; x++)
{
cout << myArray[x] << " ";;
}
delete[]myArray;
}
int main()
{
myClass object;
object.storeData(object.size, object.(&myArray)[]);
// E0133 expected a member name.
object.printData(object.size, object.(&myArray)[]);
// E0133 expected a member name.
}
这里有几个问题,我将尽量解决它们。
将数组传递给函数时,永远不要使用[]
语法。在C和c++中,数组衰变成指针,所以我们不需要[]
和&
。
这是传递数组的有效语法:
int my_array [] = {1,2,3,4};
my_function(my_array, 4);
…
void my_function(int * array, size_t size)
{
//Iterate over the array or do something...
}
此外,如果函数存在于类中,则它可以自由地访问类成员,这意味着我们根本不必传递它们。请参阅以下对代码的更改:
void myClass::storeData(int size)
// Stores array data. We do NOT need a pointer to the object array, we already have it!
{
cout << "Enter Size of the array: ";
cin >> size;
// User determines array size.
for (int x = 0; x < size; x++)
{
cout << "Array[" << x << "]: ";
cin >> myArray[x];
// User determines array values.
cout << endl;
}
}
最后,动态大小的数组必须动态分配。不要在类定义中使用int* myArray = new int[size];
,因为size
还没有初始化。相反,使用构造函数或store_data函数来分配内存。
class myClass
{
public:
size_t size;
int * myArray; //Do not allocate anything here...
myClass(size_t size)
{
this->size = size;
myArray = new int[size];
}
};
你可以通过用户输入等方式获得你想要的大小,并将其传递给构造函数或分配器函数,如storeData。