-5

I have been given a header file called lexer.h and it predefines a class called Token. However, I don't understand the constructor. Given lexer.h below how would I, for instance, create an instance of Token with a TokenType = T_ID , lexeme = "this" , lnum = 2 ? Thanks!

#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
    It seems like you really need to read a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Rakete1111 Oct 13 '17 at 16:04

2 Answers2

1

An object of type token can be created in three ways because of the default arguments in the constructor.

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

The latter two will have the member variables as defined in de constructor.

Haas
  • 21
  • 4
0

That class is a bit funky because it initializes lnum from an external variable. It really should come from an argument to the constructor. But since that's the way it is, you can't control it, other than by setting the value of lineNumber, which probably isn't what was intended; its value probably comes from wherever the input is being processed, and gets incremented at each new line.

So to create an object of that type, just do it:

Token t(T_ID, "this");
Pete Becker
  • 74,985
  • 8
  • 76
  • 165