以下是此代码问题的一些注释。
class foo{
int oldarray[1]; //Do you really want an array of size 1? Why not just an integer?
enum unit {values};//An enumeration that only enumerates one thing? Are you sure you don't really want const int VALUES = 0; I feel like you don't really even want an enum
public:
int createNewArray() const;
};
int foo::createNewArray() const {
int newarray[50]; //Magic numbers are bad, what if sizeof(oldarray) > 50?
int oldarray = oldarray[values]; //Re declaring oldarray as a single integer and assigning it oldarray[values] as its value.
int size = (sizeof(oldarray)); //is this oldarray an integer or an array of integers???
for (int i = 0; i > size; i++){ //don't you want i < size??? if size > 0, this loop will never get run.
if (oldarray[i] > 0) //probably grabbing the correct oldarray(Compilers are smart), but not getting expected values because the array version of oldarray wasn't initialized properly.
newarray[i] = oldarray[i];
}
我相信你试图做的是以下几点:
int* foo::createNewArray() const {
const int SIZE = sizeof(oldarray);
int *newArray = int[SIZE];
for(int i = 0; i < SIZE; i++) {
if(oldarray[i] > 0) {
newArray[i] = oldarray[i];
} else {
newArray[i] = 0;//In most environments this is unnecessary, but it is safer and good style
}
}
return newArray;
}
请注意,即使此代码也仅在 oldarray 在此代码范围内时才有效(不是很好的样式,将其作为参数传递给 createNewArray 会更好,但没关系)并且已正确实例化,因此 sizeof(oldarray) 是数组的大小而不是整数的大小,或者可能是整数指针,我忘记了。