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
Comments
Leave a comment