Введение
void read_foo (std::ifstream& out);
void write_foo (std::ofstream& out);
У меня есть эти две функции, где нужно читать из файла, а другой должен писать в один.
Все работает с нижеприведенными фрагментами;
std::ifstream ifs ("filename.txt");
read_foo (ifs);
std::ofstream ofs ("filename.txt");
write_foo (ofs);
ПРОБЛЕМА
Однако, если я пытаюсь использовать std::fstream
, поэтому я могу вызывать обе функции с одним потоком, он не компилируется, а компилятор выдает много сообщений об ошибках.
- Почему я не могу привязать
fstream
кifstream&
илиofstream&
?
foo.cpp
#include <fstream>
void read_foo (std::ifstream& out);
void write_foo (std::ofstream& out);
int main () {
std::fstream fs ("filename.txt");
read_foo (fs);
write_foo (fs);
}
Ошибка (ы):
foo.cpp: In function ‘int main()’:
foo.cpp:9:16: error: invalid initialization of reference of type ‘std::ifstream& {aka std::basic_ifstream<char>&}’ from expression of type ‘std::fstream {aka std::basic_fstream<char>}’ read_foo (fs);
^
foo.cpp:3:7: note: in passing argument 1 of ‘void read_foo(std::ifstream&)’ void read_foo (std::ifstream& out);
foo.cpp:10:16: error: invalid initialization of reference of type ‘std::ofstream& {aka std::basic_ofstream<char>&}’ from expression of type ‘std::fstream {aka std::basic_fstream<char>}’
write_foo (fs);
^
foo.cpp:4:6: note: in passing argument 1 of ‘void write_foo(std::ofstream&)’ void write_foo (std::ofstream& out);