Answer to Question #317966 in C++ for Muhammad Usman

Question #317966

1. Write C++ program, overload the unary decrement operator (--) , postix nd prefix





2. Write C++ program , overload the binary subtraction operator(-)




1
Expert's answer
2022-03-25T04:37:19-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog