3

私は通訳を開発していますが、いくつか質問があります。

私は最近、言語のすべてのオブジェクト/値に対して以下のような非常に単純な構造体を使用する小さな C インタープリターを見ました。

struct Object
{
    ubyte type;
    ubyte value;
};

この構造体は、インタープリターが使用している言語で使用される文字列、整数、ブール値、およびリスト (と思います) を保持できます。

  • この Object 構造体にこれらすべての型を保持させるにはどうすればよいでしょうか?
4

2 に答える 2

2

この Object 構造体にこれらすべての型を保持させるにはどうすればよいでしょうか?

値を保持するのではなく、別の場所に格納されている値への ID/参照を保持するだけです。

于 2010-05-29T10:10:17.020 に答える
1

Most likely, it's done like sbi suggests, so the interpreter's struct would look more like:

struct Object
{
    ubyte type;
    void* value;
};

The actual value would be allocated somewhere on the heap, and when the object was constructed, the interpreter would note the type in ubyte type. Later, functions would note the type using object.type and alias the value to that type, or just assume that it was the correct type, like this:

useObjectAsString(Object toUse) 
{
    char* data = (char*)toUse.value;
}

If you just have a few types you want to implement, you could also try using a union.

于 2012-03-06T01:04:58.480 に答える