-
February 4th, 2014, 06:19 PM
#1
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;
}
-
February 4th, 2014, 07:47 PM
#2
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;
Last edited by Philip Nicoletti; February 4th, 2014 at 07:59 PM.
-
February 5th, 2014, 06:29 AM
#3
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
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|