Bài tập C++ OOP: tạo các lớp trừu tượng | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Write a program to create abstract class Shape and 2 classes Rectangle, Circle as below:

Explanation:

Shape class (abstract class)

  • getArea() and getPerimeter() are two abstract methods used for calculating the circumference and area of object.

Rectangle class

  • length and width: properties describe the length and width of a rectangle.
  • rectangle(length: double, width: double): the constructor that initializes values for properties.
  • getArea() and getPerimeter(): are overridden methods from interface IShape, they return the circumference and area of the rectangle.

Circle class

  • radius: property that describes the radius of a circle.
  • Circle(radius: double): the constructor that that initializes values for radius property.
  • getArea() and getPerimeter(): are overridden methods from interface IShape, they return area and circumference of the circle respectively (π = 3.14).

A program to test the result:

#include <iostream>
#include "Shape.cpp"
#include "Rectangle.cpp"
#include "Circle.cpp"

using namespace std;

int main() {
    Shape** shapes = new Shape * [3];
    shapes[0] = new Rectangle(3.4, 5.3);
    shapes[1] = new Circle(5.5);
    shapes[2] = new Rectangle(7.4, 4.3);
    for (int i = 0; i < 3; i++) {
        cout << "Area of shapes[" << i << "]: " << shapes[i]->getArea() << endl;
        cout << "Perimeter of shapes[" << i << "]: " << shapes[i]->getPerimeter() << endl;
    }
    return 0;
}

When the above code is compiled and executed, it produces the following result:

Area of shapes[0]: 18.02
Perimeter of shapes[0]: 17.4
Area of shapes[1]: 94.985
Perimeter of shapes[1]: 34.54
Area of shapes[2]: 31.82
Perimeter of shapes[2]: 23.4

Instruction

Code sample:

Shape.cpp file

#pragma once

class Shape {
public:
	virtual double getArea() = 0;
	virtual double getPerimeter() = 0;
};

Rectangle.cpp file

#include "Shape.cpp"

class Rectangle : public Shape {
private:
    double length;
    double width;

public:
    Rectangle(double length, double width) {
        this->length = length;
        this->width = width;
    }

    double getArea() {
        return length * width;
    }

    double getPerimeter() {
        return (length + width) * 2;
    }
};

Circle.cpp file

#include "Shape.cpp"

class Circle : public Shape {
private:
    double radius;

public:
    Circle(double radius) {
        this->radius = radius;
    }

    double getArea() {
        return 3.14 * radius * radius;
    }

    double getPerimeter() {
        return 2 * 3.14 * radius;
    }
};