简体   繁体   中英

Cannot find Overloaded operator<<

I have a draw function that returns vector< >.

vector< vector<char> > draw(char penChar, char fillChar) const{
        const int breadth = this->height;
        const int length = this->width;
        vector< vector<char> > temp(breadth, vector<char>(length));
        for (int x = 0; x <= height - 1; x++) {
            for (int y = 0; y <= width - 1; y++) {
                temp[0].push_back(penChar);
            }
        }

        return temp;
    }

I overloaded the operator<< like this

friend ostream& operator<<(ostream& os,  const vector< vector<char> >& grid) {
        for (const vector<char>& vec : grid) {
            for (const char& ch : vec) {
                os << ch;
            }
            os << "\n";
        }
        return os;
    }

But when I run cout << rect.draw('2', 'w') << endl; I get the following error.

entererror: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::vector<std::vector<char> >’)
cout << rect.draw('2', 'w') << endl;

Can someone tell why the compiler cannot find this method? Also I have another operator<

friend ostream& operator<<(ostream& os, const Shape& obj) {
        //Some code
  return os;
    }

But this seems to work fine.

You should simply put the function ostream& operator<<(ostream& os, const vector< vector<char> >& grid) outside the class and without friend, like this:

class Foo
{
  //draw function and other stuff
};

ostream& operator<<(ostream& os,  const vector< vector<char> >& grid)
{
}

Since in the function you defined there is no variable of (in this example) Foo class the ADL (Argument-dependent lookup) cannot be used so if you defined the function inside the class compiler cannot find it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM