tellg() 用于 const 引用对象。“复制”fstream 对象

Iva*_*ush 2 c++

我正在编写一个处理文本文件的类。我想“复制” ifstream-object 属性。下面的代码显示了我是如何做到的。我的函数 w.m_fin.tellg()有问题:

  • 错误 C2662: 'std::basic_istream<_Elem,_Traits>::tellg':无法将 'this' 指针从 'const std::ifstream' 转换为 'std::basic_istream<_Elem,_Traits> &'

我想在目标对象中设置文件位置,就像在源中一样。如果我将参数设置为非 const [ Word(Word& w) ] ,则一切正常。但我不想让它变得非常量。我应该怎么做才能解决这个问题?

谢谢

class Word
{
private:
    std::ifstream m_fin;
    std::string m_in_filename;

public:

    Word(const Word& w):  m_in_filename( w.m_in_filename ) 
    {
        m_fin(m_in_filename);
        m_fin.copyfmt( w.m_fin );                                  
        m_fin.clear( w.m_fin.rdstate() );
        m_fin.seekg( w.m_fin.tellg() );//here I get an error
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*son 6

由于 b tellg(通过可能设置fail状态)更改了流的状态(当然,查找和任何形式的读或写操作也是如此),因此您不能在对象上执行此操作const。但是,如果您想以这种方式解决它,我希望您可以声明m_finmutable,这意味着编译器甚至允许对对象进行更改const