1. Write C++ program, overload the unary decrement operator (--) , postix nd prefix
2. Write C++ program , overload the binary subtraction operator(-)
#include <iostream>
using namespace std;
class Integer {
int value;
public:
Integer(int v=0) : value(v) {}
void print(ostream& os) const { os << value; }
// Prefix:
Integer& operator++() { value++; return *this; }
// Postfix:
Integer operator++(int) {
Integer tmp = *this;
value++;
return tmp;
}
friend ostream& operator<<(ostream& os, const Integer& i);
};
ostream& operator<<(ostream& os, const Integer& i) {
i.print(os);
return os;
}
int main() {
Integer i(1);
cout << "i = " << i;
cout << "; i++ = " << i++ << endl;
cout << "i = " << i;
cout << "; ++i = " << ++i << endl;
cout << "i = " << i << endl;
return 0;
}
#include <iostream>
using namespace std;
class Integer {
int value;
public:
Integer(int v=0) : value(v) {}
void print(ostream& os) const { os << value; }
// Prefix:
Integer& operator++() { value++; return *this; }
// Postfix:
Integer operator++(int) {
Integer tmp = *this;
value++;
return tmp;
}
Integer operator-(const Integer& other) const {
return Integer(value - other.value);
}
friend ostream& operator<<(ostream& os, const Integer& i);
};
ostream& operator<<(ostream& os, const Integer& i) {
i.print(os);
return os;
}
int main() {
Integer i1(10);
Integer i2(8);
cout << i1 << " - " << i2 <<" = " << i1 - i2 << endl;
return 0;
}
Comments
Leave a comment