简体   繁体   中英

Difficulty in unary operator overloading in C++?

I was just reading about unary operator overloading using minus(-),increment(++).etc. I thought to write a code for the same just for practice.But when I tried to run it it give me error for both minus and increment operator.I think the problem is the way I'm calling the operator in main.Can anyone please what's the correct way of doing this ?

#include<iostream>

using namespace std;

class c{
   int x;
   int y;
   public:
      c(int a,int b){
             x=a;
             y=b;   
      }

      void operator -(){
             x=x+1;
             y=y+1;
      }

      void display(){
             cout<<x<<" "<<y<<"\n";
      }

};

int main()
{
     c obj(2,3);
     obj.display();
         obj- ;    //I think the error is on this line
     obj.display();
     return 0;
}

If I replace obj- with -obj the code works fine.Why is it so ? Same is the problem with ++ operator overloading(using ++obj works fine but obj++ doesn't work),why ?

Thanks.

The unary minus operator - is a prefix operator only.

to overload suffix version of the ++ operator, you need a dummy int parameter. eg

struct foo
{
    void operator - ()
    {
        std::cout << "hello" << std::endl;
    }

    void operator ++ (int)
    {
        std::cout << "world" << std::endl;
    }
};

int main()
{
    foo bar;
    -bar;
    bar++;
}

First, you can't invent new operators, only redefine existing ones, so your unary post-minus can't be done. The post-decrement operator is (of course) two minus signs, not just one.

Secondly, when you define an increment or decrement operator, you give the function an (unused) int argument to distinguish the pre- form from the post-form; if the function has the argument, then it's a post-increment or post-decrement operation, but without it, it's pre-increment/pre-decrement.

The unary - operator is the negation operator. It's what happens when you say -5 or -var . You don't say 5- or var- . If you're after var - 3 , overload the binary operator.

The postincrement operator has a dummy int argument to distinguish it from the preincrement operator.

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