问题描述
我想初始化大小的数组N系从我的构造函数的输入参数。
这工作:
I am trying to initialize an array of size n based off the input argument of my constructor.This works:
//Inside Header
class runningAverage{
private:
byte n;
float array[10];
public:
runningAverage(byte);
};
//Inside .cpp
runningAverage::runningAverage(byte a){
n = a;
for (byte i = 0; i<n; i++) {
array[i] = 0;
}
}
和这不起作用:
//Inside Header
class runningAverage{
private:
byte n;
float array[];
public:
runningAverage(byte);
};
//Inside .cpp
runningAverage::runningAverage(byte a){
n = a;
for (byte i = 0; i<n; i++) {
array[i] = 0;
}
}
我要初始化数组,这样由n指定的大小。这样,我不要随意指定float数组[256]或类似的东西浪费内存。任何帮助AP preciated!
I want to initialize the array so that is the size specified by n. This way I don't waste memory by arbitrarily specifying float array[256] or something like that. Any help is appreciated!
推荐答案
您有实际分配数组;你会想用一个指针类型, int数组[]
是不是你想在那里。由于juanchopanza提醒我们,你也想要么禁止拷贝构造函数和赋值运算符,或实现那些做一个适当的深层复制。
You have to actually allocate the array; and you'll want to use a pointer type, float array[]
is not what you think there. As juanchopanza reminds us, you'll also want to either disable the copy constructor and assignment operator, or implement ones that do a proper deep copy.
//Inside Header
class runningAverage{
private:
byte n;
float *array; // <= correct type
public:
runningAverage(byte);
~runningAverage(); // <= you'll need a destructor to cleanup
private:
runningAverage(const runningAverage &);
runningAverage & operator = (const runningAverage &);
};
//Inside .cpp
runningAverage::runningAverage(byte a){
array = new float[n]; // <= allocate array
n = a;
for (byte i = 0; i<n; i++) {
array[i] = 0;
}
}
// clean up
runningAverage::~runningAverage(){
delete[] array;
}
不过,如果您在您的处置有一些动态的,全自动的容器(如的std ::矢量
),你可能想使用代替 - 那么你不必对付拷贝/转让/析构函数/内存管理。
However, if you have some dynamic, automatic container at your disposal (e.g. std::vector
) you might want to use that instead - then you don't have to deal with copy / assignment / destructor / memory management.
这篇关于初始化变量大小的数组类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!