简体   繁体   中英

overloading operators error: no matching function

I have this overloaded operator in my FileDir.cpp implementation file:

 std::ostream& operator<< (std::ostream &out, const FileDir &obj) {
        out << obj.toString();
        return out;
 }

This is my toString() function:

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;
}

Here is the error I get:

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*’

This is my FileDir.h header file:

#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;

};

I think there's a problem with my toString() declaration, but I'm not sure.

How do I fix the error?

You didn't declare toString as a const member function (a function that can be called on a const object). The parameter obj in operator<< is const , so toString must be as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM