Consider the base class shape,
shape.h
#ifndef shape_h #define shape_h #include <string> class shape { public: virtual double area() = 0; virtual double perimeter() = 0; void describe(); virtual std::string name(); protected: std::string color; }; #endif
shape.cpp
#include "shape.h" #include <iostream> using namespace std; void shape::describe() { cout << "The " << color << " " << name() << " has an area of " << area() << " and a perimeter of " << perimeter() << endl; } string shape::name() { return("shape"); }
Note that here the virtual functions area() and
perimeter() are
declared =0 to indicate they have no implementation in the base class.
A derived class for a rectangle might be as follows,
rectangle.h
#ifndef rectangle_h #define rectangle_h #include "shape.h" class rectangle : public shape { public: rectangle(std::string color, double width, double height); double area(); double perimeter(); std::string name(); private: double width; double height; }; #endif
rectangle.cpp
#include "rectangle.h" #include <iostream> using namespace std; rectangle::rectangle(string c, double w, double h) { color=c; width=w; height=h; } double rectangle::area() { return(width*height); } double rectangle::perimeter() { return(2*width+2*height); } string rectangle::name() { return("rectangle"); }
and finally the test program,
test.cpp
#include "rectangle.h" #include <vector> int main() { std::vector<shape*> shapes; rectangle r1("green", 10, 4); rectangle r2("red", 5, 8); shapes.push_back(&r1); shapes.push_back(&r2); for(int i=0; i<shapes.size(); i++) shapes[i]->describe(); return 0; }
int max() and int
min() which
return the maximum and minimum values of the matrix. Add test cases
to the main function.==' for the operator '!='. Add test cases to the main
functionvoid
read(std::istream& in=std::cin) which
enables the matrix to be set to an appropriate number of
integers separated by spaces. Add test cases to the main function<<' for output
streams which allows the matrix to be used in input streams
using the '>>' operator. Add test cases to the
main function