Hint of operator overloading

D

dover

Could somebody give hints about writing overloading of post-increment and
pre-increment operators? Thanks!
 
D

Dave Townsend

Here, try this. The trick is the dummy parameter (int) in the pre-increment
operator, which is used to disambiguate the ++foo and foo++ operators.

dave

class foo
{

public:
foo( int i )
:_i(i)
{}
foo()
:_i(0)
{}
// pre-increment ++foo
foo operator++()
{
_i++;
return *this;
}
// post increment foo++
foo operator++(int )
{
foo tmp = *this;
_i++;
return tmp;

}
int toInt()
{
return _i;
}
private:
int _i;

};



#include "stdafx.h"

int main(int argc, char* argv[])
{

foo f(10);
foo g(10);
foo gnew(++g);
foo fnew(f++);

int gi = g.toInt();
int fi = f.toInt();

int gnewi = gnew.toInt();
int fnewi = fnew.toInt();


return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top