错误:"运算符<<不匹配

error: no match for ‘operator<<’

本文关键字:lt 不匹配 运算符 错误      更新时间:2023-10-16

这是我的运算符<<实现:

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

我在 FileDir 类声明之后将这一行添加到我的 FileDir 头文件中:

std::ostream& operator<< (std::ostream &out, FileDir &obj);

在我的 FileDirTest 中,为了测试运算符<<,我有以下内容:

assert(cout << t1 == "testFileOne 50kb");

(其中 t1 是文件目录)

这是我得到的错误:

error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘FileDir’)
assert(cout << t1 == "testFileOne 50kb");

另外,这是完整的头文件:

 #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;
};
std::ostringstream& operator<< (std::ostringstream &out, FileDir &obj);

这是我的 toString():

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

这是导致错误的FileDirTest部分:

static void OperatorsTest() {
        FileDir t1("testFileOne", 50, false);
        FileDir t2("testDirectory", 100, true);
        FileDir t3("testFileTwo", 20, false);
        assert(t1 < t2);
        assert(t3 < t2);        
        std::ostringstream oss; 
        oss << t1;
        assert(oss.str() == "testFileOne 50kb");        
    }

更新:事实证明我的头文件以前已经编译过,所以我对它所做的任何更改都没有通过。一旦我删除了.gch文件,FileDirTest终于编译了。