88.6k views
4 votes
C++ Programming

Create a class template Pair that houses 2 items of datatype T.
Whatever datatype stored needs to implement the < and > operators.
There should be two private data attributes called item1 and item2.
There should be the following public methods.

A 2 argument constructor.
A method getMax that returns the larger of the two stored items.
A method getMin that returns the smaller of the two stored items.
A method setItems that takes in two constant items by reference and sets item1 and item2 to them.
A method getItem1 that returns item1.
A method getItem2 that returns item2.

Make a appropriate methods const so they don't alter item1 or item2 if not needed.

You should have a Pair.h and Pair.cpp file.

Create a pairTest.cpp file with a main() that creates two pairs, one that houses ints an one that houses strings.
Test all the methods for these two Pairs in your main and display the results.

1 Answer

7 votes

Answer:

Step-by-step explanation:

Please find the code below::

Pair.h

#ifndef PAIR_H_

#define PAIR_H_

#include <iostream>

using namespace std;

template <class T>

class Pair{

private:

T item1,item2;

public:

Pair(T itemOne,T itemTwo);

T getMax()const;

T getMin() const;

void setItems(const T &itemOne,const T &itemTwo);

T getItem1();

T getItem2();

};

#endif /* PAIR_H_ */

Pair.cpp

#include "Pair.h"

template<class T>

Pair<T>::Pair(T itemOne,T itemTwo){

item1 = itemOne;

item2 = itemTwo;

}

template<class T>

T Pair<T>::getMax() const{

if(item1>item2){

return item1;

}else{

return item2;

}

}

template<class T>

T Pair<T>::getMin()const{

if(item1<item2){

return item1;

}else{

return item2;

}

}

template<class T>

void Pair<T>::setItems(const T &itemOne,const T &itemTwo){

item1 = itemOne;

item2 = itemTwo;

}

template<class T>

T Pair<T>::getItem1(){

return item1;

}

template<class T>

T Pair<T>::getItem2(){

return item2;

}

TestMain.cpp

#include "Pair.h"

#include "Pair.cpp"

#include <iostream>

using namespace std;

int main() {

Pair<int> p(2,3);

cout<<"Max is "<<p.getMax()<<endl;

cout<<"Min is "<<p.getMin()<<endl;

p.setItems(10,20);

cout<<"getItem1 : "<<p.getItem1()<<endl;

Pair<double> p2(2.5,3.5);

cout<<"Max is "<<p2.getMax()<<endl;

cout<<"Min is "<<p2.getMin()<<endl;

p2.setItems(10.5,20.5);

cout<<"getItem1 : "<<p2.getItem1()<<endl;

return 0;

}

User Natashia
by
4.0k points