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
  • 607
  • 4
  • 10
  • 24
  • 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
  • 78,542
  • 46
  • 206
  • 285
  • ok, but now the error is [Linker error] undefined reference to `operator<<(std::ostream&, VertexPriority&)' I changed a bit your code because it doesn't let me use pointers(vp->priority) so I used the already implemented getter (vp.getVertex) – giacomotb Nov 03 '13 at 10:46
  • Fixed, I don't know why but I deleted a 'const' before VertexPriority in the function declaration – giacomotb Nov 03 '13 at 10:49
  • If you used `getVertex` and that was not declared `const`, then you would need to. – Paul Draper Nov 03 '13 at 10:52