开发者

Solution to a static indexed value

Pleas开发者_StackOverflow社区e see the following code:

#include <iostream>
#include <string>

using namespace std;

enum dataType {
    DATATYPE_BYTE,
    DATATYPE_CHAR, 
    DATATYPE_UCHAR,
    DATATYPE_SHORT,
    DATATYPE_USHORT,
    DATATYPE_INT,
    DATATYPE_UINT,
    DATATYPE_LONG,
    DATATYPE_ULONG,
    DATATYPE_FLOAT,
    DATATYPE_UFLOAT,
    DATATYPE_DOUBLE,
    DATATYPE_UDOUBLE,

    DATATYPE_BLOB,
    DATATYPE_STRING,
    DATATYPE_COMPLEX, 

    DATATYPE_MORE, 
    DATATYPE_ERROR
};

typedef struct typenamepair_ {
    const dataType name;
    const char* const nameval ;
} typenamepair;

class types {
    private:
        typenamepair *typesArr;
        static typenamepair TYPES[];
        static types* instance_;
    public:
        static types* getInstance() {
            if ( !instance_ )
                instance_ = new types;

            return instance_;
        }
        const char* operator[](dataType typeEnum)
        {
            for ( unsigned int i = 0; i < (sizeof(types::TYPES)/sizeof(typenamepair)); ++i ) {
                if ( i == TYPES[i].name  )
                    return TYPES[i].nameval;
            }
            // failed to get value. return error
            return TYPES[DATATYPE_ERROR].nameval;
        }
};

types* types::instance_ = NULL;
typenamepair types::TYPES[] = {
    { DATATYPE_BYTE, "byte" },
    { DATATYPE_CHAR, "char" },
    { DATATYPE_UCHAR, "u_char" },
    { DATATYPE_SHORT, "short" },
    { DATATYPE_USHORT, "u_short" },
    { DATATYPE_INT, "int" },
    { DATATYPE_UINT, "u_int" },
    { DATATYPE_FLOAT, "float"},
    { DATATYPE_UFLOAT, "u_float"},
    { DATATYPE_DOUBLE, "double"},
    { DATATYPE_UDOUBLE, "u_double"},
    { DATATYPE_STRING, "cstring"},
    { DATATYPE_BLOB, "blob"},
    { DATATYPE_COMPLEX, "complex"},
    { DATATYPE_MORE, "more"},

    // Unknown type!
    { DATATYPE_ERROR, "ERROR"}
};


main()
{
    const char* test = (types::getInstance())[DATATYPE_UINT] ;
    cout << test << endl;
}

Gives me the following compilation errors:

test.cpp: In member function 'const char* types::operator': test.cpp:53: error: invalid application of 'sizeof' to incomplete type 'typenamepair []' test.cpp: In function 'int main()': test.cpp:87: error: cannot convert 'types' to 'const char*' in initialization

What is wrong with size of and how can I fix it? Also, how can I use the returned instace to use the operator to get the typename?

Also, please let me know if there is a better solution. Thanks


For your first error, you need to move the code using sizeof until after the array contents have been defined. There is a better way to get the array size but it also can't be used until the contents are defined.

For your second error, you have a pointer, so your user-defined operator[] isn't being found. Change getInstance to return a reference instead of a pointer and it should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜