3

This is my operator<< implementation:

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

I have added this line to my FileDir header file, after the FileDir class declaration:

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

In my FileDirTest, in order to test the operator<<, I have the following:

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

(where t1 is a FileDir)

This is the error I get:

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

Also, here is the complete header file:

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

This is my 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;
}

And this is the part of FileDirTest that causes the error:

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

    }
13
  • The obj parameter should probably be a const reference. Apr 16, 2015 at 0:10
  • 1
    And that's definitely not how you test what was printed out.
    – T.C.
    Apr 16, 2015 at 0:11
  • Also, what do you the the relative priorities of << and == are? Because cout doesn't return a string. Apr 16, 2015 at 0:11
  • How would I check for the correct output with cout then? Apr 16, 2015 at 0:15
  • Perhaps something like this? cout << t1; std::string str = cout.str(); assert(str == "testFileOne 50kb"); Apr 16, 2015 at 0:19

1 Answer 1

0

Update: Turns out that my header file had been compiled previously, so any of the changes I'd been making to it didn't go through. Once I deleted the .gch file, FileDirTest finally compiled.

Not the answer you're looking for? Browse other questions tagged or ask your own question.