pedr0 pedr0 - 2 months ago 10
C++ Question

no known conversion for argument 1 from ‘Graph<int>*’ to ‘Graph<int>&’

I can't understand the problem I am facing here :

class Dijkstra {
public:
Dijkstra(Graph<T> &graph, bool verbose = false)
:m_graph(graph), m_verbose(verbose){ }

[ .. ]
}

Graph<int> *custom = Graph<int>::custom((int *) &nodes[0], 4, 5);
Dijkstra<int> spt(custom, true);


Isn't the Dijkstra constructor taking a reference, and if so, why on earth is the compiler complaining ?

graph.cpp:222:37: error: no matching function for call to ‘Dijkstra<int>::Dijkstra(Graph<int>*&, bool)’
Dijkstra<int> spt(custom, true);
^
graph.cpp:222:37: note: candidates are:
graph.cpp:128:3: note: Dijkstra<T>::Dijkstra(Graph<T>&, bool) [with T = int]
Dijkstra(Graph<T> &graph, bool verbose = false)
^
graph.cpp:128:3: note: no known conversion for argument 1 from ‘Graph<int>*’ to ‘Graph<int>&’


graph.cpp:126:7: note: Dijkstra::Dijkstra(const Dijkstra&)
class Dijkstra {

I have the feeling I am getting it wrong, all of it.

Answer

A pointer and a reference are 2 different things, and in a strong typed language, aren't always compatible. You should look at the doc for more information. Anyway, here is a solution for your case :

Graph<int> *custom = Graph<int>::custom((int *) &nodes[0], 4, 5);
Dijkstra<int> spt(&custom, true);

Adding & in front of a ref return the address of the object, and so is a pointer.