I don’t know Java at all, but I need this program in C++. Can anyone help me convert it? I know OOP in C++, but I’m used to another syntax and do not understand exactly what and how to modify it.
class Graph { class Edge { int src, dest; } int vertices, edges; Edge[] edge; Graph(int vertices, int edges) { this.vertices = vertices; this.edges = edges; edge = new Edge[edges]; for (int i = 0; i < edges; i++) { edge[i] = new Edge(); } } public static void main(String[] args) { int i, j; int numberOfVertices = 6; int numberOfEdges = 7; int[][] adjacency_matrix = new int[numberOfEdges][numberOfEdges]; Graph g = new Graph(numberOfVertices, numberOfEdges); g.edge[0].src = 1; g.edge[0].dest = 2; //do something with graph } }
I tried to do that and I optinut the code below:
class Graph { public: class Edge { private : Graph *parentClass; public: Edge(Graph *parentClass) { this->parentClass = parentClass; } int src; int dest; }; int vertices; int edges; std::vector<Graph::Edge::Edge*> edge; //error 1 qualified reference to 'Edge' is a constructor name rather than a type in this context Graph(int vertices, int edges) { this->vertices = vertices; this->edges = edges; edge = std::vector<Graph::Edge::Edge>(edges); //err 2 no viable overloaded '=' //err 3 qualified reference to 'Edge' is a constructor name rather than a type in this context for (int i = 0; i < edges; i++) { edge[i] = new Graph::Edge::Edge(); //err 4 no matching constructor for initialization of 'Graph::Edge::Edge' } } };
But the code that I got myself, has a number of errors
Advertisement
Answer
In the case of your mentioned error 1 and 3, “qualified reference to ‘Edge’ is a constructor name rather than a type in this context” that you mention in your question title the error is because you are using the constructor where the compiler would expect to see a type.
You have:
Graph - this is a class Edge - this is a nested class Edge - the constructor for the Edge class
So when you refer to Graph::Edge
that is the class, but Graph::Edge::Edge
is the constructor function.
Replace your usage of Graph::Edge::Edge
with Graph::Edge
to solve that error.
You also have problems where you mix vectors of pointers and vectors of instances.
Your final error 4 is because you are not using the constructor that you have defined (wrong parameters).