//Rectangle.h #ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle { private: double width; double length; public: //constructor Rectangle(double w, double l); //accessor double getWidth() const; double getLength() const; double getArea() const; //mutator void setWidth(double w); void setLength(double l); }; #endif
//Rectangle.cpp #include "Rectangle.h" Rectangle::Rectangle(double w, double l):width(w), length(l){} double Rectangle::getWidth() const { return width; } double Rectangle::getLength() const { return length; } double Rectangle::getArea() const { return width*length; } void Rectangle::setWidth(double w) { width = w; } void Rectangle::setLength(double l) { length = l; }
//main.cpp #include <iostream> #include "Rectangle.h" int main(int argc, char *argv[]) { Rectangle *r; r = new Rectangle(5, 10); std::cout<<"Area: "<<r->getArea()<<std::endl; return 0; }
//V.h #ifndef V_H #define V_H class V { private: int size; double *array; public: V(int s); V(double *a, int s); int getSize() const; double *getArray() const; void display() const; ~V(); }; #endif //V.cpp #include <cstdlib> #include <iostream> #include "V.h" V::V(int s) { std::cout<<"Constructor V(s) ..."<<std::endl; size = s; array = new double[size]; for(int i = 0; i < size; i++) array[i] = rand()%100; } V::V(double *a, int s) { std::cout<<"Constructor V(a, s) ..."<<std::endl; size = s; array = a; } int V::getSize() const { return size; } double *V::getArray() const { return array; } void V::display() const { for(int i = 0; i < size; i++) std::cout<<array[i]<<" "; std::cout<<std::endl; } V::~V() { std::cout<<"Destructor "<<size<<" ..."<<std::endl; size = 0; delete [] array; //array = 0; } //main.cpp #include <iostream> #include <cstdlib> #include "V.h" int main(int argc, char *argv[]) { V v(5); v.display(); V *v2 = new V(10); v2->display(); delete v2; double *array = new double [15]; for(int i = 0; i < 15; i++) array[i] = rand()%100; V *v3 = new V(array, 15); v3->display(); delete v3; return 0; }