Post increment in operator overloading in c++

This is my post increment operator overloading declaration.

loc loc::operator++(int x)
{
    loc tmp=*this;
    longitude++;
    latitude++;
    retrun tmp;
} 

My class constructor

loc(int lg, int lt) 
{
   longitude = lg;
   latitude = lt;
}

In main function, I have coded like below

int main()
{
    loc ob1(10,5);
    ob1++;
}

While compiling this , i am getting the below error

opover.cpp:56:5: error: prototype for 'loc loc::operator++(int)' does not match any in class 'loc' opover.cpp:49:5: error: candidate is: loc loc::operator++() opover.cpp: In function 'int main()': opover.cpp:69:4: error: no 'operator++(int)' declared for postfix '++'


Fix your class declaration from

class loc
{
    // ...
    loc operator++();
} 

to

class loc
{
    // ...
    loc operator++(int);
} 

[ Edit removed misguided remarks about returning by value. Returning by value is of course the usual semantics for postfix operator++]


you should have two versions of ++ :

loc& loc::operator++() //prefix increment (++x)
{
    longitude++;
    latitude++;
    return *this;
} 

loc loc::operator++(int) //postfix increment (x++)
{
    loc tmp(longtitude, langtitude);
    operator++();
    return tmp;
}

And, of course, both functions should be defined in class prototype:

loc& operator++();
loc operator++(int);

You didn't declare the overloaded operator in your class definition.

Your class should look something like this:

class loc{
public:
    loc(int, int);
    loc operator++(int);
    // whatever else
}

** edit **

After reading the comments, I noticed that in your error message it shows that you declared loc operator++() , so just fix that.

链接地址: http://www.djcxy.com/p/73144.html

上一篇: 通过const值返回的目的?

下一篇: 在c ++中增加运算符重载