Basics of C/C++ Programming Practice 7 Code
From ICO wiki
Jump to navigationJump to search
Shape
shape.h
#pragma once class Shape { protected: int numAngles; public: Shape(int angles); virtual ~Shape(); int getNumAngles(); virtual double area() = 0; };
shape.cpp
#include "Shape.h" Shape::Shape(int angles) : numAngles(angles) { } Shape::~Shape() { } int Shape::getNumAngles() { return numAngles; }
Circle
circle.h
#pragma once #include "Shape.h" class Circle : public Shape { double radius; public: Circle(double newRadius); ~Circle(); virtual double area() override; };
circle.cpp
#include "Circle.h" #include <cmath> Circle::Circle(double newRadius) : Shape(0), radius(newRadius) { } Circle::~Circle() { } double Circle::area() { return 3.1415 * pow(radius, 2); }
Rectangle
rectangle.h
#pragma once #include "Shape.h" class Rectangle : public Shape { double width; double height; public: Rectangle(double newWidth, double newHeight); ~Rectangle(); virtual double area() override; };
rectangle.cpp
#include "Rectangle.h" Rectangle::Rectangle(double newWidth, double newHeight) : Shape(4) , width(newWidth) , height(newHeight) { } Rectangle::~Rectangle() { } double Rectangle::area() { return width * height; }
main
main.cpp
#include <memory> #include <vector> #include <iostream> #include "Circle.h" #include "Rectangle.h" int main() { std::vector<std::unique_ptr<Shape>> shapes; shapes.push_back(std::make_unique<Rectangle>(2, 3)); shapes.push_back(std::make_unique<Circle>(2)); double totalArea = 0; for (std::unique_ptr<Shape>& shape : shapes) { std::cout << shape->getNumAngles() << std::endl; } return 0; }