operator overloading (prefix ++)
Hi...
I am writing the overloading operator function (prefix ++) according to my book.. but it doesnt work !!!!!!
But if i write:
void operator++()
{
++x;
}
it works !!!!!
Is the book wrong???
Here is my code according to the book that doesnt work as it should:
#include <iostream>
using namespace std;
class things
{
int x,y,z;
public:
void print()
{
cout<<x<<endl;
cout<<y<<endl;
cout<<z<<endl;
cout<<"*****"<<endl;
}
things():x(0),y(0),z(0){};
thing& operator ++() //******** here *******
{
++x;
return *this;
}
};
int main()
{
things table;
cout<<"*****"<<endl;
table.print();
++table;
table.print();
return 0;
}
Re: operator overloading (prefix ++)
You have:
Code:
thing & operator ++() //******** here *******
It should be things &
Also, the problem with the void method is that you can not use operator ++
in many ways that you would expect to .. Example:
Code:
things table2 = ++table;
Re: operator overloading (prefix ++)
Please format your code properly before posting and use code tags (Go advanced, select the code and click '#'). You code as posted is not very readable.
When overloading the operator ++, there are two situations that need to be considered - pre and post increment.
Prefix increment is defined as
Code:
things& operator++();
whereas postfix increment is defined as
Code:
things operator++(int);
See
http://msdn.microsoft.com/en-us/library/f6s9k9ta.aspx