Answer to Question #222492 in C++ for Jaguar

Question #222492
Overload the +, - and * operators for objects of class Pairs in question 4, as
member functions. Also define the class Pairs as an ADT that uses separate files
for the interface and the implementation. Use separate compilation and the same
program as in question 4 to test these member functions.
1
Expert's answer
2021-08-02T07:15:44-0400

file: main.cpp

#include <iostream>
using namespace std;
#include "Pairs.h"

int main()
{
    Pairs p1(5,10),p2(2,8);
    
    cout << "p1 : " << endl;
    p1.display();
    cout << "\np2 : " << endl;
    p2.display();
    
    Pairs p3 = p1 + p2;
    cout << "\np3 = p1 + p2\np3 : " << endl;
    p3.display();
    
    Pairs p4 = p1 - p2;
    cout << "\np4 = p1 - p2\np4 : " << endl;
    p4.display();
    
    Pairs p5 = p1 * p2;
    cout << "\np5 = p1 * p2\np5 : " << endl;
    p5.display();
    
    return 0;
}

file: Pairs.h

class Pairs{
    double a,b;
    
    public :
    Pairs();
    Pairs(double a, double b);
    Pairs operator + (Pairs const &obj);
    Pairs operator - (Pairs const &obj);
    Pairs operator * (Pairs const &obj);
    void display();
};

file: Pairs.cxx

#include <iostream>
using namespace std;
#include "Pairs.h"

Pairs::Pairs()
{}
    
Pairs::Pairs(double a, double b)
{
    this->a = a;
    this->b = b;
    
}
    
    //following is the + operator for add the objects of class Pairs
Pairs Pairs::operator + (Pairs const &obj) {
    Pairs res;
    res.a = a + obj.a;
    res.b = b + obj.b;
    return res;
}
    
Pairs Pairs::operator - (Pairs const &obj) {
    Pairs res;
    res.a = a - obj.a;
    res.b = b - obj.b;
    return res;
}

Pairs Pairs::operator * (Pairs const &obj) {
    Pairs res;
    res.a = a * obj.a;
    res.b = b * obj.b;
    return res;
}
    
void Pairs::display()
{
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
}

Output:

p1 :
a = 5
b = 10

p2 :
a = 2
b = 8

p3 = p1 + p2
p3 : 
a = 7
b = 18

p4 = p1 - p2
p4 :
a = 3
b = 2

p5 = p1 * p2
p5 :
a = 10
b = 80

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
APPROVED BY CLIENTS