如何在给定此定义的情况下创建类的实例

How to create an instance of a class given this definition

本文关键字:情况下 创建 实例 定义      更新时间:2023-10-16

我得到了一个名为lexer.h的头文件,它预定义了一个名为Token的类。但是,我不了解构造函数。给定下面的lexer.h,例如,我将如何创建一个令牌实例,其TokenType = T_ID,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_ */

由于构造函数中的默认参数,可以通过三种方式创建 token 类型的对象。

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

后两者将具有在 de 构造函数中定义的成员变量。

该类有点时髦,因为它从外部变量初始化lnum。它确实应该来自构造函数的参数。但是既然是这样,你无法控制它,除了通过设置lineNumber的值,这可能不是预期的;它的值可能来自处理输入的任何地方,并在每个新行处递增。

因此,要创建该类型的对象,只需执行此操作:

Token t(T_ID, "this");