这是我的运营商<<实现:
std::ostream& operator<< (std::ostream &out, FileDir &obj) {
out << obj.toString();
return out;
}
在FileDir类声明之后,我已将此行添加到我的FileDir头文件中:
std::ostream& operator<< (std::ostream &out, FileDir &obj);
在我的FileDirTest中,为了测试运算符&lt;&lt;,我有以下内容:
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");
}
答案 0 :(得分:0)
更新:事实证明我的头文件已经被编译过,所以我所做的任何改变都没有通过。删除.gch文件后,FileDirTest最终编译完毕。