Hi iam new to c++.
i have learn operator overloading and write one program but it shows errors.
i dont understand whats wrong with the code.please anyone help me with this.
the program is of overloading operator ++(increment)& --(decrement).
If you want to focus on the increment and decrement operators, it might make things less complicated if you try to not use a class.(There are errors are some errors with the way you use the class)
I think using increments and decrements with for loops might be a good idea to start.
Try making a loop that increments/decrements a number 5 times and prints out each increment/decrement.
Your overloads of operator++ and operator-- are both prefix versions.
But your main is using postfix versions.
Postfix versions are defined by including a "dummy" int parameter.
#include <iostream>
usingnamespace std;
class Test {
int a;
public:
Test() {
a=0;
}
// Prefix operators
Test operator++() {
++a;
return *this;
}
Test operator--() {
--a;
return *this;
}
// Postfix operators
Test operator++(int) {
Test t = *this; // for postfix, you need to return a copy of the object before the change
++a;
return t;
}
Test operator--(int) {
Test t = *this;
--a;
return t;
}
void show() {
cout << "a value is:" << a << '\n';
}
};
int main() {
Test t1;
Test t2 = t1++;
t1.show();
t2.show();
t2 = ++t1;
cout<<'\n';
t1.show();
t2.show();
t2 = t1--;
cout<<'\n';
t1.show();
t2.show();
t2 = --t1;
cout<<'\n';
t1.show();
t2.show();
return 0;
}