Operator overload ==

0
bool Stock::operator== (const Stock& stk){

if ( this->get_resource() == (stk.get_resource()) )
    return true;
else
    return false;
}

I created this method to overload the operations of a class, however, when I instantiate pointers of this class and initialize them, I set values and see if one object is equal to the other method that should return TRUE , since the values are the same, it does not return.

int main (){

    Stock* stk1 = new Stock();
    Stock* stk2 = new Stock();

    stk1->set_resource(10);
    stk2->set_resource(10);

    cout << stk1->get_resource() << endl;
    cout << stk2->get_resource() << endl;

    if(stk1 == stk2)
        cout << "IGUAL" << endl;

    return 0;
}

if never runs.

    
asked by anonymous 20.02.2017 / 01:36

1 answer

2

The error is in a part of the code that was not shown by the OP.

I am putting the modified code because the original code is a bad example of C ++.

#include <iostream>
using namespace std;

class Stock
{
   private:
      int resource;

   public:
      int get_resource() { return resource; }
      void set_resource(int r) { resource = r; }
      bool operator==(const Stock& stk) { return resource == stk.resource; }
};

int main ()
{
    Stock stk1, stk2;

    stk1.set_resource(10);
    stk2.set_resource(10);

    cout << stk1.get_resource() << endl;
    cout << stk2.get_resource() << endl;

    if (stk1 == stk2)
       cout << "IGUAL" << endl;
    else
       cout << "DIFERENTE" << endl;

   return 0;
}
    
20.02.2017 / 02:23