[英]overloading operators error: no matching function
我的FileDir.cpp實現文件中有這個重載的運算符:
std::ostream& operator<< (std::ostream &out, const FileDir &obj) {
out << obj.toString();
return out;
}
這是我的toString()函數:
string FileDir::toString()
{
std::string whatever;
std::stringstream converter;
converter << size;
converter >> whatever;
std::string combined;
if (type == false) {
combined = name + " " + whatever + "kb";
}
if (type == true) {
combined = name + "/" + " " + whatever + "kb";
}
return combined;
}
這是我得到的錯誤:
FileDir.cpp: In function ‘std::ostream& operator<<(std::ostream&, const FileDir&)’:
FileDir.cpp:125:25: error: no matching function for call to ‘FileDir::toString() const’
out << obj.toString();
^
FileDir.cpp:125:25: note: candidate is:
FileDir.cpp:84:8: note: std::string FileDir::toString() <near match>
string FileDir::toString()
^
FileDir.cpp:84:8: note: no known conversion for implicit ‘this’ parameter from ‘const FileDir*’ to ‘FileDir*’
這是我的FileDir.h頭文件:
#include <sstream>
class FileDir {
public:
FileDir();
FileDir(std::string nameVal, long sizeVal = 4, bool typeVal = false);
FileDir(const FileDir &obj);
~FileDir(); // destructor
long getSize() const;
std::string getName() const;
bool isFile() const;
std::string rename(std::string newname);
long resize(long newsize);
std::string toString();
bool operator== (const FileDir &dir1);
bool operator<(const FileDir &obj);
private:
std::string name;
long size;
bool type;
};
我認為我的toString()聲明有問題,但我不確定。
如何解決錯誤?
您沒有將toString
聲明為const
成員函數(可以在const
對象上調用的const
)。 operator<<
的參數obj
是const
,因此toString
必須是。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.