[英]ostream::operator<< is not working with operator-> in shared_ptr
#include<fstream>
#include<string>
#include<memory>
class Log
{
private:
string errorlog;
shared_ptr<ofstream> fs;
public:
Log() :errorlog(""), fs(new ofstream("c:\\Log\\log.txt"), [](ofstream& fs) {fs.close(); })
{
}
void transferLog(string errorlog)
{
(*fs)<<(errorlog) //is working
fs->operator<<(errorlog); //not working
}
}
我知道如果可行,在其他常見情況下也可以正常工作。
此錯誤列表
no instance of overloaded function "std::basic_ofstream<_Elem, _Traits>::operator<< [with _Elem=char, _Traits=std::char_traits<char>]" matches the argument list
好吧,那就不要那樣做。
可以通過以下兩種方式之一定義重載的operator<<
。 它可以定義為成員函數,可以稱為fs->operator<<(errorlog);
,或者可以將其定義為獨立函數,可以將其稱為operator<<(*fs, errorlog);
。
對於標准輸出流,某些重載使用第一種形式,而其他重載使用第二種形式。 如果您選擇了錯誤的形式,那么事情就會破裂。 除非您有一個非常特殊的用例,需要使用其中一個,否則只需編寫*fs << errorlog;
:同時考慮兩種形式,並從兩種形式中選擇最佳的重載形式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.