문제

클래스 메소드 나 생성자까지 배열의 크기를 정의하는 방법이 있습니까?

내가 생각하는 것은 다음과 같이 보일 수 있습니다. 물론 작동하지 않습니다.

class Test
{
    private:
    int _array[][];

    public:
    Test::Test(int width, int height);
};

Test::Test(int width, int height)
{
    _array[width][height];
}
도움이 되었습니까?

해결책

다니엘이 말하는 것은 테스트 (너비, 높이) 메소드가 호출 될 때 배열에 대한 메모리를 동적으로 할당해야한다는 것입니다.

이와 같은 두 차원을 선언합니다 (정수 배열을 가정) :

int ** _array;

그런 다음 테스트 방법에서 먼저 포인터 배열을 할당 한 다음 각 포인터마다 정수 배열을 할당해야합니다.

_array = new  *int [height];
for (int i = 0; i < height; i++)
{
    _array [i] = new int[width];
}

그런 다음 객체가 릴리스되면 할당 한 메모리를 명시 적으로 삭제해야합니다.

for (int i = 0; i < height; i++)
{
    delete [] _array[i];
    _array [i] = NULL;
}
delete [] _array;
_array = NULL;

다른 팁

벡터는 당신의 가장 친한 친구입니다

class Test
{
    private:
    vector<vector<int> > _array;

    public:
    Test(int width, int height) :
        _array(width,vector<int>(height,0))
    {
    }
};

나는 당신이 새로운/삭제 연산자를 찾아야 할 때라고 생각합니다.

이것이 다차원 배열이라는 것을 보면, 당신은 갈 때 '새'라고 부르면서 루프를해야합니다.

비록 많은 사람들이 너비*높이 요소가있는 1 차원 배열을 사용하도록 제안 할 것이라고 확신합니다.

(몇 달 후) 다음과 같이 템플릿을 사용할 수 있습니다.

// array2.c
// http://www.boost.org/doc/libs/1_39_0/libs/multi_array/doc/user.html
// is professional, this just shows the principle

#include <assert.h>

template<int M, int N>
class Array2 {
public:
    int a[M][N];  // vla, var-len array, on the stack -- works in gcc, C99, but not all

    int* operator[] ( int j )
    {
        assert( 0 <= j && j < M );
        return a[j];
    }

};

int main( int argc, char* argv[] )
{
    Array2<10, 20> a;
    for( int j = 0; j < 10; j ++ )
    for( int k = 0; k < 20; k ++ )
        a[j][k] = 0;

    int* failassert = a[10];

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top