gpt4 book ai didi

c++ - 错误 : no match for ‘operator<<’

转载 作者:太空狗 更新时间:2023-10-29 23:15:21 25 4
gpt4 key购买 nike

<分区>

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

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 是一个 FileDir)

这是我得到的错误:

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

}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com