Don't know how to add prefixes/postfixes to objects

Don't know how to add prefixes/postfixes to objects in my program

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <iostream>
using namespace std;

class Square {

private:
	double side;


public:

	double getArea() {
		return side * side;
	}

	void setSide(double s) {
		side = s;
	}




	// Overload + operator to add two Square objects.
	Square operator+(const Square& b) {
		Square square;
		square.side = side + b.side;
		return square;
	}

	Square operator-(const Square& b) {
		Square square;
		square.side = side - b.side;
		return square;
	}


	Square operator*(const Square& b) {
		Square square;
		square.side = side * b.side;
		return square;

	}

	Square operator/(const Square& b) {
		Square square;
		square.side = side / b.side;
		return square;
	}

	Square operator>(const Square& b) {
			Square square;
			square.side = side > b.side;
			return square;

	}
//I want to add a -- decrememt prefix or postfix here
	Square operator--(const Square& b) {
		Square square;
		square.side = side -- b.side;
		return square;

	}

};

// Main function
int main() {
	using namespace std;
	Square Square1;
	Square Square2;
	Square Square3;
	double area = 0.0;


	Square1.setSide(2.0);

	Square2.setSide(5.0);


	// Square1 area
	area = Square1.getArea();
	cout << "Area of Square1 : " << area << endl;

	// Square2 area
	area = Square2.getArea();

	cout << "Area of Square2 : " << area << endl;

	char op;

	cout << "Enter the operator: ";
	cin >> op;
	switch (op)
	{
	case '+':
		Square3 = Square1 + Square2;
		cout << Square3.getArea();
		break;
	case '-':
		Square3 = Square1 - Square2;
		cout << Square3.getArea();
		break;
	case '*':
		Square3 = Square1 * Square2;
		cout << Square3.getArea();
	case '>':
		Square3 = Square1 > Square2;
		cout << Square3.getArea();
		break;
	case 'Q':
		exit;
	default:
		cout << "No a valid operator";
	}
	system("pause");
	return 0;
}
Lines 50-55: operator > should return a bool. Your line 52 will evaluate side > b.side which results in a bool (0 or 1). That 0 or 1 is then stored in side. Probably not what you want.

1
2
3
4
5
6
bool operator > (const Square& b) 
{  bool rslt;
	
    rslt = (side > b.side);
    return rslt;
}


Line 57-64: There are two forms of the decrement operator. prefix and postfix. The prefix operator takes no arguments. The postfix operator takes a dummy int.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//  Prefix decrement	
Square & operator-- () 
{   --square.side; 
	return *this;
}

//  Postfix decrement
Square operator-- (int) 
{   Square temp;

    temp.side = side;
	side--; 
	return temp; 
}





Topic archived. No new replies allowed.