简体   繁体   中英

Overloading operator to use with another class in C++

Is there any way to overload the > (greater than) operator, to be able to do something like:

myClass *a = new myClass(1);
myClass *b = new myClass(3);

if(a > b) //it should compare the int values from the constructors
  //do something

I've tried overloading the operator, but got various errors. I am using VC++.

You cannot overload operators for pointers, because they are primitive types (and you cannot create an overload where both arguments are primitive types); instead, you can overload the operators for your objects of user-defined types (not pointer to them):

class myClass
{
    // ...
public:
    bool operator>(const myClass & right) const
    {
        return this->whatever()>right.whatever();
    }
};

myClass *a = new myClass(1);
myClass *b = new myClass(3);

if(*a > *b) //it should compare the int values from the constructors
  //do something

notice that, if you don't have a particular reason to allocate stuff on the heap, it's much better to just allocate it on the stack:

myClass a(1);
myClass b(3);
if(a > b)
    // do something

Try

class MyClass
{
    int value;
    public:
        bool operator>(MyClass const& rhs) const
        {
             return value > rhs.value;
        }

        MyClass(int v):value(v){}

};

int main()
{
     MyClass a(1);
     MyClass b(3);

     if (a > b) { PLOP } else { POOP }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM