C ++ ifstream类型不完整 [英] C++ ifstream has incomplete type
本文介绍了C ++ ifstream类型不完整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在修改一个项目,我想将输出写入文件.在我的 .hpp
文件中,我声明了一个文件流,如下所示:
I'm modifying an project where I want to write an output to a file. In my .hpp
file I declared a file stream like so:
// fname.hpp file
#include <fstream>
std::ifstream m_ifs = ("path_to_file");
然后在我的 .cpp
文件中
// fname.cpp
if (!m_ifs.is_open()) {
std::cerr << "Not writing to file" << std::endl;
return;
}
m_ifs << "Write something"
但是当我编译时,出现以下错误:
But when I compile I get the following error:
error: field ‘m_ifs’ has incomplete type ‘std::ifstream {aka std::basic_ifstream<char>}’
/usr/include/c++/5/iosfwd:116:11: note: declaration of ‘std::ifstream {aka class std::basic_ifstream<char>}’
class basic_ifstream;
错误指向我在 hpp
文件上的声明.
The error points to my declaration on the hpp
file.
我在网上找到的解决方案无法解决问题.
The solutions I found on the web didn't solve the problem.
以下工作有效:
// fname.hpp file
#include <fstream>
const std::string m_file = ("path_to_file");
std::fstream m_fs;
和
// fname.cpp
m_fs.open(m_file.c_str());
if (!m_fs.is_open()) {
std::cerr << "Not writing to file" << std::endl;
return;
}
m_fs << "Write something"
推荐答案
对我来说,它似乎是一个全局变量.如果确实如此,请通过以下方式声明它们:
It looks like a global variable to me. If it indeed is, declare them the following way:
//fname.hpp:
const std::string m_file = ("path_to_file");
std::fstream m_fs;
和
// fname.cpp
m_fs.open(m_file.c_str());
if (!m_fs.is_open()) {
std::cerr << "Not writing to file" << std::endl;
return;
}
m_fs << "Write something"
此外,您无法写入ifstream.将其更改为ofstream或fstream.
Also, you can't write to ifstream. Change it to ofstream or fstream.
这篇关于C ++ ifstream类型不完整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文