The following program overloads the increment operator ++ relative to the class coord.
// overload the ++ relative to coord class
#include
using namespace std;
class coord {
int x, y; // coordinate values
public:
coord( ) { x = 0; y = 0; }
coord(int i, int j) { x = i; y = j; }
void get_xy(int &i, int &j) { i = x; j = y; }
coord operator++( );
};
// Overload ++ operator for coord class
coord coord::operator++( ) {
x++;
y++;
return *this;
}
int main( ) {
coord o1(10, 10);
int x, y;
++o1; //increment an object
o1.get_xy(x, y);
cout << "(++o1) X: " << x << ", Y: " << y << "\n";
return 0;
}
In early versions of C++ when increment or decrement operator was overloaded, there was no way to determine whether an overloaded ++ or -- preceded or followed its operand (i.e. ++o1; or o1++; statements). However in modern C++, if the difference between prefix and postfix increment or decrement is important for you class objects, you will need to implement two versions of operator++( ). The first is defined as in the preceding example. The second would be declared like this:
coord coord::operator++(int notused);
If ++ precedes its operand the operator++( ) function is called. However, if ++ follows its operand the operator++(int notused) function is used. In this case, notused will always be passed the value 0. Therefore, the difference between prefix and postfix increment or decrement can be made.
In C++, the minus sign operator is both a binary and a unary operator. To overload it so that it retains both of these uses relative to a class that you create: simple overload it twice, once as binary operator and once as unary operator. For example,
// overload the - relative to coord class
#include
using namespace std;
class coord {
int x, y; // coordinate values
public:
coord( ) { x = 0; y = 0; }
coord(int i, int j) { x = i; y = j; }
void get_xy(int &i, int &j) { i = x; j = y; }
coord operator-(coord ob2); // binary minus
coord operator-( ); // unary minus
};
// Overload binary - relative to coord class.
coord coord::operator-(coord ob2) {
coord temp;
temp.x = x - ob2.x;
temp.y = y - ob2.y;
return temp;
}
// Overload unary - for coord class.
coord coord::operator+( ) {
x = -x;
y = -y;
return *this;
}
int main( ) {
coord o1(10, 10), o2(5, 7);
int x, y;
o1 = o1 - o2; // subtraction
// call operator-(coord)
o1.get_xy(x, y);
cout << "(o1-o2) X: " << x << ", Y: " << y << "\n";
o1 = -o1; // negation
// call operator-(int notused)
o1.get_xy(x, y);
cout << "(-o1) X: " << x << ", Y: " << y << "\n";
return 0;
}
No comments:
Post a Comment