1

I get the compiler error

no match for 'operator<<' in 'std::cout << VertexPriority(2, 4u)' 

In the main class referred to this operator overloading, but I can't undestand where the error is.

Here there is the operator overloading line, I implemented it inside the class definition.

std::ostream& operator<<(std::ostream& out) const { return out << "Vertex: " << this->vertex << ", Priority: " << this->priority; }

vertex and priority are integer and unsigner integer.

In the main class I'm trying to doing this:

std::cout << VertexPriority(2, 3) << std::endl;
giacomotb
  • 507
  • 3
  • 9
  • 23
  • You don't define insertion operators like that, unless it is your intention to insert an ostream in to your object (which I can all-but-guarantee it is *not*). See the section on common operator overloading [in this answer](http://stackoverflow.com/questions/4421706/operator-overloading-in-c/4421719#4421719). – WhozCraig Nov 03 '13 at 10:40
  • how should I define it? – giacomotb Nov 03 '13 at 10:42
  • See the linked article in my prior comment [**or click here**](http://stackoverflow.com/questions/4421706/operator-overloading-in-c/4421719#4421719) – WhozCraig Nov 03 '13 at 10:42

1 Answers1

2

Define it like this:

class VertexPriority {
    ...

    friend std::ostream& operator<< (std::ostream& out, const VertexPriority& vp);
};

std::ostream& operator<< (std::ostream& out, const VertexPriority& vp) {
    return out << "Vertex: " << vp.vertex << ", Priority: " << vp.priority;
}

The friend keyword is necessary if VertexPriority::vertex or VertexPriority::priority are not public.

For more help, read this tutorial: http://www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/

Paul Draper
  • 71,663
  • 43
  • 186
  • 262