我已經給出了一個名爲lexer.h的頭文件,它預先定義了一個名爲Token的類。但是,我不明白構造函數。舉個例子,下面給出lexer.h,我將如何使用TokenType = T_ID創建一個Token實例,lexeme =「this」,lnum = 2?謝謝!如何根據定義創建類的實例
#ifndef LEXER_H_
#define LEXER_H_
#include <string>
#include <iostream>
using std::string;
using std::istream;
using std::ostream;
enum TokenType {
// keywords
T_INT,
T_STRING,
T_SET,
T_PRINT,
T_PRINTLN,
// an identifier
T_ID,
// an integer and string constant
T_ICONST,
T_SCONST,
// the operators, parens and semicolon
T_PLUS,
T_MINUS,
T_STAR,
T_SLASH,
T_LPAREN,
T_RPAREN,
T_SC,
// any error returns this token
T_ERROR,
// when completed (EOF), return this token
T_DONE
};
class Token {
TokenType tt;
string lexeme;
int lnum;
public:
Token(TokenType tt = T_ERROR, string lexeme = "") : tt(tt), lexeme(lexeme) {
extern int lineNumber;
lnum = lineNumber;
}
bool operator==(const TokenType tt) const { return this->tt == tt; }
bool operator!=(const TokenType tt) const { return this->tt != tt; }
TokenType GetTokenType() const { return tt; }
string GetLexeme() const { return lexeme; }
int GetLinenum() const { return lnum; }
};
extern ostream& operator<<(ostream& out, const Token& tok);
extern Token getToken(istream* br);
#endif /* LEXER_H_ */
看來你真的需要閱讀[好書](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – Rakete1111