我必须围绕liblas reader类编写一个包装器。我想在构造函数中创建reader实例并将其保存在成员变量中。
class LASPointReader : PointReader{
private:
liblas::Reader reader;
...
}
这是我认为可行的:
LASPointReader::LASPointReader(string file){
ifstream ifs;
ifs.open(file, std::ios::in | std::ios::binary);
liblas::ReaderFactory f;
reader = f.CreateWithStream(ifs);
...
}
但由于liblas :: reader没有默认构造函数,因此失败了。然后我尝试使reader变量成为指针并执行
reader = &f.CreateWithStream(ifs);
哪个失败,因为现在我在使用阅读器时在运行时收到“R6025 - 纯虚函数调用”错误。
然后我尝试了一个相当难看的初始化列表:
LASPointReader::LASPointReader(string file)
: reader(liblas::ReaderFactory().CreateWithStream(ifstream(file, std::ios::in | std::ios::binary)))
{
但是现在,读者只能部分工作。它确实可以加载文件的头部,但另一个应该读取内容的方法失败。
我应该如何将这个读者实例存储在我的班级?
答案 0 :(得分:6)
C ++流是不可复制的。这意味着CreateWithStream()
没有选择,只能通过引用获取流并存储该引用。这反过来意味着它只有在它引用的流有效时才有效。在初始化列表的情况下,这只是在初始化结束之前。 (我猜你正在使用Visual Studio,否则编译器会抱怨它不能将rvalue绑定到非const引用)。
如果是这种情况,只要有读者,就必须确保流有效。这意味着使流也成为数据成员。在C ++中,成员总是按照类中的声明顺序初始化,所以这样做:
class LASPointReader : PointReader{
private:
std::ifstream stream;
liblas::Reader reader;
...
}
LASPointReader::LASPointReader(string file)
: stream(file, std::ios::in | std::ios::binary)
, reader(liblas::ReaderFactory().CreateWithStream(stream))
{