C++
これは、s を使用して書き込むことができる限り、<<
an の演算子を使用した出力動作を模倣するクラスを作成する試みです。このクラスには、ポインターという 1 つのデータ メンバーがあります。このクラスには 2 つのオーバーロードされた演算子があります。1 つは を受け取り、もう 1 つは関数へのポインターを受け取ります。引数は参照であり、参照を返します。これによると、それは の署名です。技術的には、以下のプログラムは指定された入力で動作します。2 つの s で区切られた 2 行のテキストをファイルに出力できます。ただし、文字列以外のパラメーターのオーバーロードされたオペレーターが受け入れてほしいofstream
std::endl
string
ofstream
<<
std::string
ostream
ostream
std::endl
std::endl
<<
std::endl
単にその署名に一致するものではありません。with と without 、 withstd::endl
と without 、引数リストに配置するさまざまな組み合わせを試しましたが、すべての組み合わせでコンパイラエラーが発生しました。C++11 の回答も歓迎します。*
&
#include <fstream>
#include <iostream>
#include <string>
class TextOut
{
public:
TextOut(std::ofstream* ofsPar) : ofs(ofsPar) {}
TextOut& operator<<(std::string s)
{
*ofs << s;
return *this;
}
TextOut& operator<<(std::ostream& (*endlPar) (std::ostream& os))
{
*ofs << std::endl;
return *this;
}
private:
std::ofstream* ofs;
};
int main()
{
std::cout << "Enter filename: ";
std::string filename;
std::cin >> filename;
std::ofstream myofstream(filename.c_str());
TextOut myTextOut(&myofstream);
myTextOut << "Hello," << std::endl << std::endl << "spacious world.";
return 0;
}
出力:
Hello,
spacious world.