C ++ overloading `-`

I have overloaded the operator for "-" for my class graph. It's not completely intuitive (bad coding - I know), but if I do graph3 = graph2-graph1 then graph 3 should only get those vertices in both graph 2 and graph 1.

So I wrote the code and when I run the debugger the function statement seems to create a new "graph" to return and add the corresponding vertices to the new graph and after that the debugger seems to exit the function but never returns it back to the main ... It's like he's waiting for me to type something. No error messages are displayed.

Here is the code:

char stringy[100];
//cin>>stringy;
strcpy(stringy,"|12,34,25,2,3,2|(3->2),(2->1),(5->9),(2->1)|");
char* param= new char[sizeof(stringy)];
strcpy(param,stringy);
Graph graph1(param);

 char sstring[20] = "|33,34,11|(2->33)|";
Graph graph2(sstring);
cout<<graph2.outSumm()<<endl;

Graph graph3;
//until here everything works fine
graph3= graph1-graph2; //the debugger does this and then 

cout<<graph3.outSumm()<<endl;

      

Function operator:

Graph Graph::operator- (const Graph& g2) const
{
Graph created;

//goes through "this" list and if value exists in g2 copies it to created
for(int i=0;i<vertList.getSize();i++)
{
 if (g2.vertList.find(vertList.read(i))!=999)
 created.addVertex(vertList.read(i).getInt());
}

return created;
}

      

I am using code blocks.

Copy constructor:

Graph(const Graph& g2):      
maxVal(g2.maxVal),vertList(g2.vertList),edgeList(g2.edgeList){} ;

      

The assignment operator:

void Graph::operator= (const Graph& g2)
{
 if (this==&g2)
 {
 cout<<"not the greatest idea"<<endl;
 return;
 }

 vertList.delete_List();
 edgeList.delete_List();
 maxVal=0;

addValues(g2.outSumm());
}

      

0


a source to share


3 answers


Not definitely related to your question (although it might be), why aren't you using std :: string? And if you must use character arrays, why not:

char stringy[100] = "|12,34,25,2,3,2|(3->2),(2->1),(5->9),(2->1)|";
Graph graph1( stringy );

      

or even:



Graph graph1( "|12,34,25,2,3,2|(3->2),(2->1),(5->9),(2->1)|" );

      

Or are you storing the pointer passed to the constructor of your class? If so, then it is a bad idea and my advice for using std :: strings is doubled.

+2


a source


It looks like your code is in an infinite loop. Have you tried to hack into the debugger when the program stops?



Do you have a copy constructor defined in the Graph class? This is required in order to successfully return a value using a local variable created

.

+2


a source


Instead of embedding the operator, do the - = operator instead:

Graph& Graph::operator-=(const Graph& rhs)
{
    // remove nodes not in both Graphs

    return *this;
}

      

Then just implement the operator in terms of:

Graph Graph::operator-(const Graph& rhs)
{
    Graph temp(*this);
    temp -= rhs;
    return temp;
}

      

See if this works.

0


a source







All Articles