【发布时间】:2016-12-29 16:49:24
【问题描述】:
我遇到了一个以成员 var 作为引用的类(对 std::istream),操作符 void *() 和布尔操作符 !() 返回该引用,我想知道那会是什么为了。该类与使用配置参数对读取/解析文本文件有关。我已经从(大得多的)项目中提取了基本部分。在 qt(MSVC 2015 社区工具链)中,我必须更改 operator void *() 才能编译,但在原始 linux 系统上似乎没问题。
(在我的桌面环境中,我得到:“错误:C2440:'return': cannot convert from 'std::istream' to 'void *'”,所以我替换为对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) 调用操作符 void *()。
我的问题:
为什么要像这样使用成员 var 对 std::istream 的引用?
返回成员 var &m_in 的地址的目的是什么,因为它始终有效,因为它是成员 var(或者这不是真的?)
m_reader 的 operator *() 会返回 false 吗?我在网上搜索了一下,没有找到任何类似的在成员 var refs 上使用运算符的例子。接下来我需要看看当文件打开失败时它会做什么。
可能这段代码最初使用堆指针变量或m_in 变量的其他方法,并且在途中某处更改为普通成员变量,然后将运算符编辑为此?我认为历史并不容易获得。
感谢您的帮助,stackoverflow 很棒。
【问题讨论】:
标签: c++