2017-10-13 68 views
-5

我已經給出了一個名爲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_ */ 
+3

看來你真的需要閱讀[好書](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – Rakete1111

回答

0

該類有點時髦,因爲它從外部變量初始化lnum。它確實應該來自構造函數的一個參數。但是,既然這是事實,那麼除了通過設置lineNumber的值(這可能不是預期的)之外,您無法控制它,其值可能來自輸入處理的任何地方,並在每條新線上增加。

所以創建該類型的對象,只是做:

Token t(T_ID, "this"); 
1

型標記的對象可以是因爲在構造函數中默認參數三種方式來創建。

Token A(T_ID, "this"); 
Token B(T_STRING); 
Token C; 

後兩者將具有de構造函數中定義的成員變量。