Operator overload ==

Asked

Viewed 455 times

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, but when I prompt pointers of that class and initialize them, I set values and see if one object is equal to another the method that should return TRUE, since the values are equal, 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;
}

The if never runs.

  • Try taking the this. The error may be elsewhere in the code.

1 answer

2

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

I’m 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.