我有一個類包含std::ofstream
和std::ifstream
(一次只能激活一個)。我想超載operator()
以返回當前活動流。但std::ofstream
和std::ifstream
的常見基類型返回一個通用引用是什麼?公共父類型ifstream和ofstream
0
A
回答
2
我想超載運算符()返回當前活動流這使得絕對沒有意義和氣味就像設計缺陷。你爲什麼想要回報?那個操作員的調用者應該怎樣處理返回值?它既不能輸入也不能輸出。
我不知道你真正想做的事,但也許這樣的事情可能會爲你工作,但它的危險
template<typename T> class wrapper
{
T*const ptr;
wrapper(T*p) : ptr(p) {}
public:
bool empty() const { return ptr; }
operator T&() const
{
if(empty()) throw some_exception("trying to use empty wrapper");
return *ptr;
}
friend some_class;
};
class some_class
{
ifstream _ifstream;
ofstream _ofstream;
bool ifstream_is_active;
bool ofstream_is_active;
public:
operator wrapper<ifstream>() const
{ wrapper<ifstream>(ifstream_is_active? &_ifstream : 0); }
operator wrapper<ofstream>() const
{ wrapper<ofstream>(ofstream_is_active? &_ofstream : 0); }
};
但這是危險的,因爲你可能處理懸擺指針。你可以通過使用shared_ptr
(自己工作)來避免這種情況,但這意味着some_class
不再控制這些流的生命週期。
1
相關問題
- 1. Ifstream和Ofstream問題
- 2. ifstream - > ofstream C++
- 3. ifstream ofstream on mac
- 4. ifstream和ofstream在崩潰後不工作
- 5. PHP和類:獲得父母的公共財產父類中
- 6. C++公共和私有數據類型
- 7. 使用ifstream和ofstream與cin和cout之間的區別
- 8. Python類和公共成員
- 9. Netbeans警告:通過公共API導出非公共類型
- 10. 通過公共API導出非公共類型
- 11. 無法使用std :: getline()與ifstream和ofstream一起工作
- 12. 無法使用ifstream和ofstream序列化二進制數據
- 13. ifstream和ofstream:如何對文件執行多重修改?
- 14. C++ ifstream類型錯誤
- 15. 非公共類
- 16. 通過公共API導出non_public類型
- 17. VBA按流程使用公共類型
- 18. 在公共C++ API中的類型
- 19. 在公共API使用可空類型
- 20. JavaScript中的原型/類/公共屬性
- 21. 允許公共數據類型
- 22. 的Java公共接口和公共類在同一個文件
- 23. 只能由其父類實例化的c#公共類
- 24. 從不同包中的類調用公共類的公共類
- 25. XML在兩種類型(公共和Web服務類型)之間的序列化
- 26. Django模型 - 共享公共基類的不同對象類型的外鍵
- 27. JavaScript:公共方法和原型
- 28. 從公共類C#
- 29. 調用公共類
- 30. int類型的成員是否也是公共和最終的?
'std :: ios',但你真的不能用它做很多事情。 –
[This](http://cplusplus.com/reference/iostream/)和[this](http://en.cppreference.com/w/cpp/io)可能會有所幫助。 – BoBTFish