New*_*his -1 c++ class operator-overloading
我在这个头文件的 FileDir 类中有一个 operator== 类成员:
#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;
};
Run Code Online (Sandbox Code Playgroud)
这是实现:
bool operator== (const FileDir &dir1) {
if (this->name == dir1.name && this->size == dir1.size && this->type == dir1.type)
return true;
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
这是我从编译器得到的错误:
FileDir.cpp:101:37: error: ‘bool operator==(const FileDir&)’ must take exactly two arguments
bool operator== (const FileDir &dir1) {
^
make: *** [fdTest] Error 1
Run Code Online (Sandbox Code Playgroud)
我认为由于操作符是一个类成员,它应该只有一个显式参数。那么为什么会出错呢?
就像任何成员函数一样,Class::在函数体外定义函数时,需要在函数名称上加上前缀。但在这种情况下,函数的名称是operator==. 你需要:
bool FileDir::operator== (const FileDir &dir1) {
//...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6421 次 |
| 最近记录: |