0
我有這樣的重載運算符在我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()聲明有問題,但我不確定。
如何修復錯誤?
我將const添加到toString聲明中: std :: string toString()const; 抓緊實施: 串FILEDIR ::的toString()const的{ ... } 但我仍然得到錯誤。 – AbsoluteBeginner
完全相同的錯誤?你確定你保存了所有的更改? – aschepler
是的,我保存了更改。在之前的錯誤之上,現在還有一個: FileDir.cpp:84:8:錯誤:原型爲'std :: string FileDir :: toString()const'與類'FileDir'中的任何內容不匹配 string FileDir :: toString()const ^ FileDir.h:34:17:error:candidate is:std :: string FileDir :: toString() std :: string toString()const; ^ – AbsoluteBeginner