【问题标题】:overloading operators error: no matching function重载运算符错误:没有匹配的函数
【发布时间】:2015-06-20 17:48:37
【问题描述】:

我的 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() 声明有问题,但我不确定。

如何修复错误?

【问题讨论】:

    标签: c++ operator-overloading tostring


    【解决方案1】:

    您没有将toString 声明为const 成员函数(可以在const 对象上调用的函数)。 operator&lt;&lt;中的参数objconst,所以toString也必须是。

    【讨论】:

    • 我在 toString 声明中添加了 const:std::string toString() const;并执行: string FileDir::toString() const { ... } 但我仍然得到错误。
    • 完全相同的错误?您确定已保存所有更改?
    • 是的,我确实保存了更改。除了之前的错误,现在还有一个错误: FileDir.cpp:84:8: error: prototype for 'std::string FileDir::toString() const' does not match any in class 'FileDir' string FileDir: :toString() const ^ FileDir.h:34:17: 错误:候选是:std::string FileDir::toString() std::string toString() const; ^
    • @AbsoluteBeginner: 胡思乱想:问题可能是你在函数定义中使用了string 而不是std::string,所以编译器使用了另一个string 类型?
    • @FabioTurati 我将其更改为 std::string 并且仍然具有相同的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2017-08-10
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多