In: Computer Science
C++
Make this class generic so that the sides of the shape may be integer or float.
---------------shape.h------------
class Shape
{
public:
Shape();
virtual int getSide();
virtual bool setSide(int x);
virtual int getArea();
virtual int getPerimeter();
void display();
~Shape();
protected:
private:
int side;
// T_sides[numSides];
};
----------------shape.cpp----------
#include "Shape.h"
#include <iostream>
using namespace std;
Shape::Shape()
{
}
void Shape::display()
{
cout<<"side: "<<getSide()<<endl;
cout<<" area: "<<getArea()<<endl;
cout<<"perimeter: "<<getPerimeter()<<endl;
}
bool Shape::setSide(int x)
{
if(x>0){
side = x;
return true;
}else
return false;
}
int Shape::getSide()
{
return side;
}
int Shape::getArea()
{
return side*side;
}
int Shape::getPerimeter()
{
return side*4;
}
Shape::~Shape()
{
//dtor
}
int main()
{
int num;
Shape s1;
cout<<"Enter side of shape: ";
cin>>num;
if (!s1.setSide(num))
{
cout<<"Please enter a valid side."<<endl;
}
s1.display();
return 0;
}
template <class T> class Shape { public: Shape(); virtual T getSide(); virtual bool setSide(T x); virtual T getArea(); virtual T getPerimeter(); void display(); ~Shape(); protected: private: T side; // T_sides[numSides]; };
#include "Shape.h" #include <iostream> using namespace std; template <class T> Shape<T>::Shape() { } template <class T> void Shape<T>::display() { cout << "side: " << getSide() << endl; cout << " area: " << getArea() << endl; cout << "perimeter: " << getPerimeter() << endl; } template <class T> bool Shape<T>::setSide(T x) { if (x > 0) { side = x; return true; } else return false; } template <class T> T Shape<T>::getSide() { return side; } template <class T> T Shape<T>::getArea() { return side * side; } template <class T> T Shape<T>::getPerimeter() { return side * 4; } template <class T> Shape<T>::~Shape() { //dtor } int main() { int num; Shape<int> s1; cout << "Enter side of shape(int): "; cin >> num; if (!s1.setSide(num)) { cout << "Please enter a valid side." << endl; } s1.display(); return 0; }