我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?

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?

本文关键字:第一个 实例化 第二个 变量 创建 有一个 另一个 实例      更新时间:2023-10-16

我有两个类,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;
};