我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
I have a class that creates an instance of another class. How do I pass a variable through the first class into the instantiation of the second class?
我有两个类,Lexer 和 InputStream。在我的主函数中,我创建了一个 Lexer 实例,传入字符串 'filename'。我的目的是让 Lexer 将 'filename' 传递给它的成员变量 'is' 中,以便 InputStream::getChar(( 可以在 Lexer::getString(( 调用它时读出字符。我不确定如何做到这一点,因为目前,文件名可以很好地传递到Lexer中,但不会传递到InputStream的构造函数中。如何将文件名放入 InputStream 的构造函数中?
class InputStream
{
public:
InputStream(string filename)
{
in.open(filename);
}
char getChar()
{
return in.get();
}
char nextChar()
{
return in.peek();
}
private:
ifstream in;
};
class Lexer
{
public:
Lexer(string filename)
{
this->filename = filename;
}
string getString()
{
while (is.nextChar() != EOF)
{
valueSoFar.push_back(is.getChar());
}
}
private:
string valueSoFar;
string filename;
InputStream is{filename};
};
感谢您的帮助!
您可以在词法分析器类构造函数中初始化输入流实例,如下所示
class Lexer
{
public:
Lexer(string filename)
: is(filename)
{
this->filename = filename;
}
string getString()
{
valueSoFar.push_back(is.getChar());
}
private:
string valueSoFar;
string filename;
InputStream is;
};
相关文章:
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- 在类的第一个/最后一个实例存在之前/之后调用一对函数.有没有更好的方法?
- 在编译时检查未实例化的类模板是否继承自其第一个模板参数
- 有没有一种方法可以只对斜杠的第一个实例应用fnmatch的FNM_PATHNAME标志
- 编译时检查是否有两个具有相同模板参数的模板实例化
- 初始化类构造函数初始化列表中的对象数组的第一个条目
- 如何在类中初始化数组并为第一个元素设置值
- 如何实例化多个 set 对象来测试 Set 类的各种构造函数和方法
- 在第一个参数上部分专用化模板
- 使用编译器强制第一个实例
- 使用正则表达式查找多个字符串的第一个实例
- Qt / QRegularExpression - 无法捕获所有结果,只能捕获第一个实例,为什么?
- 运行while的第一个实例
- 只在类的第一个实例初始化时调用的成员函数(c++)
- 不管类是什么,c++都会找到函数的第一个实例
- 特化模板的多个实例化
- 使Qt5应用程序的第二个实例将命令行参数传输到第一个实例