error: bool operator== must take exactly two arguments

error: bool operator== must take exactly two arguments

我在这个头文件的 FileDir class 中有一个 operator== class 成员:

#include <sstream>   

class FileDir {

public:   

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

private:

    std::string name;

    long size;

    bool type;

};

这是实现:

bool operator== (const FileDir &dir1) {

    if (this->name == dir1.name && this->size == dir1.size && this->type == dir1.type)

        return true;

    else

        return false;

}

这是我从编译器得到的错误:

FileDir.cpp:101:37: error: ‘bool operator==(const FileDir&)’ must take exactly two arguments
 bool operator== (const FileDir &dir1) {
                                     ^
make: *** [fdTest] Error 1

我认为既然运算符是class成员,它应该只有一个显式参数。那为什么会报错呢?

就像任何成员函数一样,当您在主体外定义它时,您需要在函数名称上加上 Class:: 前缀。但在这种情况下,函数的名称是 operator==。您需要:

bool FileDir::operator== (const FileDir &dir1) {
    //...
}

尝试:

bool FileDir::operator== (const FileDir &dir1) const{
    if (this->name == dir1.name && 
        this->size == dir1.size && 
        this->type == dir1.type)
    return true;
else
    return false;        
}

在 class 定义中执行您的实现。

尝试:

friend bool operator==(const FileDir & dir) const;

在“xxx.h”文件中定义您的函数。 你重载了'=='符号,所以你必须将它定义为友元函数