operator overloading

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).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>
using namespace std;
class Test
{
    int a;
public:
    Test()
    {
        a=0;
    }
    void operator++()
    {
        a++;
    }
    void operator--()
    {
        a--;
    }
    void show()
    {
        cout<<"a value is:"<<a;
    }
};
int main()
{
    Test t1;
    t1++;
    t1.show();
    t1--;
    t1.show();
    return 0;
}
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
using namespace 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;
}

Last edited on
Thanks.u r right, it works.
Topic archived. No new replies allowed.