C++/Overload/Minus Minus
Overload operator "++", "--"
<source lang="cpp">
- include <iostream>
using namespace std; class array {
int nums[10];
public:
array(); void set(int n[10]); void show(); array operator++(); friend array operator--(array &ob);
}; array::array() {
int i; for(i = 0; i <10; i++) nums[ i ] = 0;
} void array::set(int *n) {
int i; for(i = 0; i <10; i++) nums[ i ] = n[ i ];
} void array::show() {
int i; for(i = 0; i <10; i++) cout << nums[ i ] << " "; cout << endl;
} // Overload unary op using member function. array array::operator++() {
int i; for(i = 0; i <10; i++) nums[ i ]++; return *this;
} // Use a friend. array operator--(array &ob) {
int i; for(i = 0; i <10; i++) ob.nums[ i ]--; return ob;
}
int main() {
array object1, object2, object3; int i[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; object1.set(i); object2.set(i); object3 = ++object1; object3.show(); object3 = --object1; object3.show(); return 0;
}
</source>
Overload the -- relative to MyClass class using a friend.
<source lang="cpp">
- include <iostream>
using namespace std; class MyClass {
int x, y;
public:
MyClass() { x=0; y=0; } MyClass(int i, int j) { x=i; y=j; } void getXY(int &i, int &j) { i=x; j=y; } friend MyClass operator--(MyClass &ob); // prefix friend MyClass operator--(MyClass &ob, int notused); // postfix
}; // Overload -- (prefix) for MyClass class using a friend. MyClass operator--(MyClass &ob) {
ob.x--; ob.y--; return ob;
} // Overload -- (postfix) for MyClass class using a friend. MyClass operator--(MyClass &ob, int notused) {
ob.x--; ob.y--; return ob;
} int main() {
MyClass object1(10, 10); int x, y; --object1; // decrement object1 an object object1.getXY(x, y); cout << "(--object1) X: " << x << ", Y: " << y << endl; object1--; // decrement object1 an object object1.getXY(x, y); cout << "(object1--) X: " << x << ", Y: " << y << endl; return 0;
}
</source>