1

C# では、関数を使用して静的配列を生成できます。

private static readonly ushort[] circleIndices = GenerateCircleIndices();

....

    private static ushort[] GenerateCircleIndices()
    {
        ushort[] indices = new ushort[MAXRINGSEGMENTS * 2];
        int j = 0;

        for (ushort i = 0; i < MAXRINGSEGMENTS; ++i)
        {
            indices[j++] = i;
            indices[j++] = (ushort)(i + 1);
        }

        return indices;
    }

C++ を使用すると、静的配列を生成する正しい方法は次のようになります。

.h

static const int BOXINDICES[24];

.cpp (コンストラクター)

static const int BOXINDICES[24] =
{ 
    0, 1, 1, 2, 
    2, 3, 3, 0, 
    4, 5, 5, 6, 
    6, 7, 7, 4, 
    0, 4, 1, 5, 
    2, 6, 3, 7 
};

circleIndices に対して同じことを行うにはどうすればよいですか?関数を使用して値を生成するにはどうすればよいですか?

.h

static const int CIRCLEINDICES[];

.cpp (コンストラクター)

static const int CIRCLEINDICES[] = GenerateCircleIndices();  // This will not work

配列要素を値 0 で初期化してから関数を呼び出す必要がありますか?

4

3 に答える 3

1

関数を実行時に評価するか、コンパイル時に評価するかによって異なります。C# では実行時に行われますが、C++ ではコンパイル時に実行するオプションが提供されます。

実行時に実行したい場合は、静的に初期化されたクラスを使用できます。

struct S
{
    int X[N];

    S() { for (int i = 0; i < N; i++) X[i] = ...; }
};

S g_s;

ここでは、配列をセットアップするために main へのエントリの前にコンストラクターが呼び出されます。

コンパイル時に実行したい場合は、C# では不可能なさまざまな方法でテンプレートまたはマクロを使用できます。コンパイル時にこれを行うと、配列のデータはコンパイラによって計算され、ローダーによってアプリケーション イメージの静的領域から直接プロセス アドレス空間に memcpy で埋められます。以下に例を示します。

#include <iostream>
#include <array>
using namespace std;

constexpr int N = 10;
constexpr int f(int x) { return x % 2 ? (x/2)+1 : (x/2); }

typedef array<int, N> A;

template<int... i> constexpr A fs() { return A{{ f(i)... }}; }

template<int...> struct S;

template<int... i> struct S<0,i...>
{ static constexpr A gs() { return fs<0,i...>(); } };

template<int i, int... j> struct S<i,j...>
{ static constexpr A gs() { return S<i-1,i,j...>::gs(); } };

constexpr auto X = S<N-1>::gs();

int main()
{
        cout << X[3] << endl;
}

参照: C++11: コンパイル時の配列の計算

于 2012-08-24T10:42:55.313 に答える
1
#include <array>        // std::array
#include <utility>      // std::begin, std::end
#include <stddef.h>     // ptrdiff_t
using namespace std;

typedef ptrdiff_t Size;

template< class Collection >
Size countOf( Collection const& c )
{
    return end( c ) - begin( c );
}

typedef array<int, 24> CircleIndices;

CircleIndices generateCircleIndices()
{
    CircleIndices   result;
    for( int i = 0;  i < countOf( result );  ++i )
    {
        result[i] = i;
    }
    return result;
}

CircleIndices const circleIndices = generateCircleIndices();

#include <iostream>
int main()
{
    for( int i = 0;  i < countOf( circleIndices );  ++i )
    {
        wcout << circleIndices[i] << ' ';
    }
    wcout << endl;
}
于 2012-08-24T10:44:23.783 に答える
1

C++ では、関数は配列を返すことができないため、配列の初期化には使用できません。あなたが持っている2つのオプションは、次のいずれかを使用することです。

static const int* CIRCLEINDICES = GenerateCircleIndices();

または

static int CIRCLEINDICES[some_size];
GenerateCircleIndices(CIRCLEINDICES);
于 2012-08-24T10:45:30.493 に答える