[英]Custom ostream prints only last string of `<<` chain
我正在嘗試使用自定義流運算符實現一個類,並從該類繼承以具有一個基類和一個具有不同流的派生類。 然后,我重載了<<
操作符以使用存儲的ostream
。
這是代碼的工作示例:
#include <string>
#include <memory>
#include <ostream>
#include <iostream>#
#include <fstream>
class Sink {
public:
Sink() {
m_stream = std::unique_ptr<std::ostream>(new std::ostream(std::cout.rdbuf()));
};
template<typename T>
std::ostream& operator<<(const T& obj) {
return *m_stream;
}
protected:
std::unique_ptr<std::ostream> m_stream;
};
class FileSink : public Sink {
public:
FileSink() {
m_stream = std::unique_ptr<std::ostream>(new std::ofstream("file.txt"));
}
};
int main() {
Sink s;
FileSink fs;
s << "First console string " << "second console string";
fs << "First file string " << "second file string";
return 0;
}
使用Sink class
我在控制台上編寫,使用FileSink
編寫在文件上。
問題在於,使用此代碼,我僅打印每條指令的最后一個字符串。
在控制台中,我看到以下輸出:
second console string
在文件中,我可以看到以下輸出:
second file string
我在做錯什么,如何打印預期的輸出?
您的operator<<
不執行任何operator<<
,並返回std::ostream&
。 然后將std::ostream::operator<<
應用於該std::ostream&
。 期待的事情!
做你想做的標准方法:
template<typename T>
Sink & Sink::operator<<(const T& obj) {
*m_stream << obj;
return *this;
}
template<typename T>
FileSink & FileSink::operator<<(const T& obj) {
*m_stream << obj;
return *this;
}
為了防止代碼重復,可以使用繼承。 我認為,它可能會復制std::stream
繼承方案。 :)
template<typename T>
std::ostream& operator<<(const T& obj) {
*m_stream << obj; // you missed this
return *m_stream;
}
另外,您可以將operator <<定義為非成員函數。
template <typename T>
Sink& operator<<(Sink &sink, const T &obj) {
*(sink.m_stream) << obj;
return sink;
}
並使其成為Sink的朋友:
class Sink {
template <typename T>
friend Sink& operator<<(Sink &sink, const T &obj);
// other code.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.