Hi, I currently have an enumeration in class Lexer:
I have an array used to get the string representations of these types:
This array is currently populated in the class's constructor:
Finally, I have a method in the class to retrieve the string representation given a lexType:
The problem with this set up is that if another class has a lexType and I simply want to get the string representation of this lexType, I have to create a new instance of the Lexer class before I can call getLexTypeName( ). Therefore, I was hoping there was some way to make getLexTypeName( ) static so I could simply call Lexer::getLexTy peName(lexType) . I know I could do something like this:
However, this seems like a very error-prone solution that depends on the order of the enumerated elements for a correct initialization. Is there some way to statically initialize the array by manually specifying the indices like I did in the constructor? If not, is there a more elegant solution for this?
Thank you,
Brian
Code:
enum lexType {
/* token keywords */
lexIF, lexTHEN, lexWHILE, lexDO, lexBEGIN, lexEND, lexELSE, lexPROGRAM,
...
/* used for array iterations */
lexENUMSIZE
};
Code:
const char* lexTypeNames[lexENUMSIZE];
Code:
Lexer::Lexer() {
lexTypeNames[lexIF] = "lexif";
lexTypeNames[lexTHEN] = "lexthen";
lexTypeNames[lexWHILE] = "lexwhile";
lexTypeNames[lexDO] = "lexdo";
lexTypeNames[lexBEGIN] = "lexbegin";
lexTypeNames[lexEND] = "lexend";
lexTypeNames[lexELSE] = "lexelse";
...
}
Code:
const char* Lexer::getLexTypeName(lexType type) const {
return lexTypeNames[type];
}
Code:
static const char* lexTypeNames[] = {"lexif", "lexthen", "lexwhile", "lexdo", ...};
Thank you,
Brian
Comment