Cannot bind error while overloading operator

My draw function returns vector<vector<char>> and I overloaded operator<< but this gives me
no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘const std::vector<std::vector<char> >’)
AND
cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’

when I run cout << rect.draw('2', 'w') << endl;

 
  const virtual vector< vector<char> > draw(char penChar, char fillChar);

1
2
3
4
5
6
7
8
9
   friend ostream& operator<<(ostream& os, vector< vector<char> >& grid) {
			for (vector<char> vec : grid) {
				for (auto ch : vec) {
					os << ch;
				}
				os << "\n";
			}
			return os;
		}
Non-const references can't bind to temporary objects.

This should work:
 
friend ostream& operator<<(ostream& os, const vector< vector<char> >& grid) {

Note that you are copying each row of the grid while iterating over it. You probably want to turn vec into a reference to avoid creating unnecessary copies.
 
for (const vector<char>& vec : grid) {
Last edited on
IDK, its still gives the same error whn I run cout << rect.draw('2', 'w') << endl;
The following code, based on your description but with Peter87‘s directions, works fine (apart from a couple of warnings referring to unused Rect::draw() parameters):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <limits>
#include <vector>

class Rect {
public:
    const virtual std::vector<std::vector<char>> draw(char penChar, char fillChar);
    friend std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<char>>& grid);
};

const std::vector<std::vector<char>> Rect::draw(char penChar, char fillChar)
{
    std::vector<std::vector<char>> myvec = { { 'a', 'b', 'c'},
                                             { 'd', 'e', 'f'} };
    return myvec;
}

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

void waitForEnter();


int main()
{
    Rect rect;
    std::cout << rect.draw('2', 'w');
    waitForEnter();
    return 0;
}

void waitForEnter()
{
    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}


Output:
abc
def

Press ENTER to continue...


The problem is: are you sure your code does what you want it to do? For example, why have you declared friend an overloaded operator which doesn’t access private members of your class?
Topic archived. No new replies allowed.