我运行一个带有成员var的类作为参考(对std :: istream),用运算符void *()和bool operator!()返回该引用,我想知道这将是什么。该类与使用config参数对读取/解析文本文件相关。我从(大部分)较大的项目中抽出了基本部分。在qt(MSVC 2015社区工具链)中,我不得不更改operator void *()
以进行编译,但在原始Linux系统上似乎没问题。参考变量的C++操作符,这有什么作用?
(在我的桌面环境,我得到:“错误:C2440:‘回归’:无法从‘的std :: istream的’转换为‘无效*’”,所以我对if(m_in.eof())
和return nullptr
的调用替换)
class LR { // (line reader)
public:
LR(const std::string &filename);
.... other stuff
operator void *() const { return &m_in; }
bool operator !() { return !m_in; }
LR & operator>>(std::string &line);
private:
std::istream &m_in; // input stream
std::ifstream m_in_file; // input file (if specified)
};
LR::LR(const std::string &filename, ... other stuff) :
: m_in(m_in_file)
{
// .... other stuff
if(filename.size() > 0)
{
m_in_file.open(filename.c_str());
}
// .... other stuff
}
,并使用这个类:
class CR { // config reader
public:
// .... other stuff
void Load_Variable(const std::string §ion, value, etc...);
private:
LR m_reader;
};
void CR::Load_Variable(const std::string §ion, value, etc.) {
string line;
bool found = false;
while (m_reader >> line)
{
// .... check stuff, etc.
}
}
调试Qt中,while (m_reader >> line)
调用操作无效*()。
我的问题:
为什么要使用成员变量引用到std::istream
这样?
返回成员变量&m_in
的地址是什么时它总是有效的,因为它是一个成员var(或不是这是真的吗?)
m_reader的operator *()
会返回false吗?我在网上搜索了一下,没有在成员var refs上找到任何类似这种操作符使用的类似示例。我需要看看文件打开失败时的功能。
可能这个代码最初使用了堆指针变量或者其他一些方法用于m_in
var,它在某种程度上被改变成了一个普通的成员变量,然后操作符被编辑为这个?我认为历史不容易得到。
感谢您的帮助,stackoverflow是真棒。
thx!很有帮助。 –