我一直在用C++編寫一些操作文件的類。當我開始時,我讓所有的構造函數接受一個std::string
參數,這個參數被解釋爲一個文件名,因爲這很快且容易。C++多態與引用
唯一功能std::fstream
任何類使用的是.open()
。我認爲,因爲std::ofstream
和std::ostringstream
都來自std::ostream
,我只使用std::ostream
的函數,所以最好讓每個構造函數適當地採用std::ostream
或std::istream
參數,而不是將類綁定到文件。
爲什麼多態性很有用的一本很好的教科書示例。雖然GCC很不高興。這是我的代碼的簡化:
#include <iostream>
#include <fstream>
class Foo {
public:
Foo(std::istream&);
std::istream& input;
};
Foo::Foo(std::istream& is) {
this->input = is;
}
int main() {
std::ifstream is("test.txt");
Foo foo(is);
}
,當與g++ test.cpp
編譯,產生錯誤的以下豐富多彩的品種:
test.cpp: In constructor ‘Foo::Foo(std::istream&)’:
test.cpp:10:1: error: uninitialized reference member ‘Foo::input’ [-fpermissive]
In file included from /usr/include/c++/4.7/ios:43:0,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from test.cpp:1:
/usr/include/c++/4.7/bits/ios_base.h: In member function ‘std::basic_ios<char>& std::basic_ios<char>::operator=(const std::basic_ios<char>&)’:
/usr/include/c++/4.7/bits/ios_base.h:791:5: error: ‘std::ios_base& std::ios_base::operator=(const std::ios_base&)’ is private
In file included from /usr/include/c++/4.7/ios:45:0,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from test.cpp:1:
/usr/include/c++/4.7/bits/basic_ios.h:64:11: error: within this context
In file included from /usr/include/c++/4.7/iostream:41:0,
from test.cpp:1:
/usr/include/c++/4.7/istream: In member function ‘std::basic_istream<char>& std::basic_istream<char>::operator=(const std::basic_istream<char>&)’:
/usr/include/c++/4.7/istream:56:11: note: synthesized method ‘std::basic_ios<char>& std::basic_ios<char>::operator=(const std::basic_ios<char>&)’ first required here
test.cpp: In constructor ‘Foo::Foo(std::istream&)’:
test.cpp:11:16: note: synthesized method ‘std::basic_istream<char>& std::basic_istream<char>::operator=(const std::basic_istream<char>&)’ first required here
我有麻煩通過所有的模板參數篩選,但它看起來像它不喜歡this->input = is;
。對於每個類都能夠作爲成員訪問流是很重要的,因爲各種不同的成員函數都必須能夠看到它。我認爲GCC可能對指針更好,但對我來說,指向類的指針看起來像動態分配的內存,我只想提出這些懷疑,如果他們是真的。什麼是正確的方式去做這件事?
很好的鏈接和很好的解釋,正是我一直在尋找。 – Monchoman45
@ Monchoman45:很高興幫助;) –