program not calling the right overloaded operator

2019-09-06 05:23发布

问题:

I've the class Directory which does stuff with objects of class File, and overloaded operators, like this:

class Directory
{
    std::vector<char> name, timeOfCreation;
    std::vector<File> arr;

public:
    Directory(std::string);
    Directory(const Directory&);
    ~Directory();


    Directory operator += (File);
    Directory operator += (Directory);
    Directory operator -= (File);
    Directory operator ~();
    File operator [] (int);
    operator int();

    friend bool operator % (Directory, File);
    friend bool operator % (Directory, Directory);
    friend Directory operator + (Directory, Directory);
    friend Directory operator - (Directory, Directory);
    friend long int operator + (Directory);
    friend std::ofstream& operator << (std::ofstream&, Directory);

friend void main();
};

Ok, now the issue arises when in main i have

void main()
{
     //make object of Directory d
    std::cout << d;
}

The program now calls the operator int() instead of operator <<. Thus the command std::cout <<d acts like std::cout << (int)d, and it writes out the number of Files in my Directory.

Here are the implementations of operators << and int():

Directory::operator int()
{
    return (int)arr.size();
}

std::ofstream& operator << (std::ofstream& out, Directory d)
{
    // get the max field widths for three fields
    int widthLeft = 0, widthMiddle = 0, widthRight = 10;
    std::vector<File>::const_iterator i = d.arr.begin();
    for(; i < d.arr.end(); ++i)
    {
        if((int)d.timeOfCreation.size() > widthLeft)
            widthLeft = (int)d.timeOfCreation.size();
    if((int)d.name.size() > widthMiddle)
            widthMiddle = (int)d.name.size();
    }
    out<<std::setw(widthLeft)<<"Date & Time of creation";
    out<<std::setw(widthMiddle)<<"Name";
    out<<std::setw(widthRight)<<"Total Size\n";
    return out;

}

Note: the operator << isn't finished yet, I'm just testing the setw function, but it still should write out that one line.

回答1:

cout is an ostream, not an ofstream.

Should work:

std::ostream& operator << (std::ostream&, Directory)

You might want to pass the directory as a reference.



回答2:

Your overloaded << should work with ostream, the base class, not just ofstream:

friend std::ostream& operator << (std::ostream&, Directory const &);

std::cout is not an ofstream, so it will not match your overload. (It's also a good idea to pass complex objects by constant reference rather than value).

Also, conversion operators are usually a bad idea, both because they can introduce unwanted implicit conversions like you found here, and because they can confuse the user of the class. It makes more sense to find the number of files in a directory through a named function (size(), or file_count(), or whatever), than by the directory itself magically changing into that particular piece of information.