如何在给定此定义的情况下创建类的实例
How to create an instance of a class given this definition
我得到了一个名为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");
相关文章:
- 是否可以在没有真实文件的情况下创建 ifstream
- 如何在不使用静态矩形方法的情况下创建 IDOMPathGeometryPtr?
- 在没有默认构造函数的情况下创建的派生对象
- 如何在没有侦听器的情况下创建 TCP 连接?
- 如何在不使用宽字符串的情况下创建目录C++?
- 是否可以在没有结构的情况下创建新的类型变量?
- 如何在不知道Arduino中知道其大小的情况下创建数组和存储值
- 如何在不使用虚拟的情况下创建装饰器函数
- 如何在给定任意数量的整数的情况下创建一个唯一键?并使用该键存储,然后从地图中查找
- 在不调用构造函数的情况下创建 Vector 元素
- 我们不能在不使用指向对象的指针的情况下创建节点C++吗?
- 在C++中,如何在没有新元素且不单独声明单个元素的情况下创建"std::initializer_list<base *>"?
- 为什么在这种情况下创建临时实例不起作用?
- 在不调用其构造函数的情况下创建对象
- 如何在不使用C 中使用新操作员的情况下创建对象
- GTKMM:如何在没有建造者的情况下创建弹出菜单
- 如何在 DPI 感知设置为DPI_AWARENESS_CONTEXT_UNAWARE的情况下创建进程
- 如何在不同步的情况下创建线程本地内存
- 如何在给定此定义的情况下创建类的实例
- 如何在不使用透明胶片的情况下创建Qt投影?(因为窗口管理器不支持)