Multi-type C++ programming language implementation

  多型的c++程式語言實作

你是個物件導向程式設計師,你首先寫了兩個 C++的類別,其程式碼如下:

Class Rectangle {

private:

float width;

float height;

public:

Rectangle(float width, float height) : width(width), height(height) { }

float getArea() const { return width * height; }

};

Class Circle {

private:

float radius;

public:

Circle(float radius): radius(radius) { }

float getArea() const { return 3.14159f * radius * radius; }

};

然後你繼續寫一個 main()來完成你的實作。你的同事會幫你完成一個 generateData()

的副程式,它會負責產生一堆 Rectangle 或 Circle 裝在一個 vector container,然後回

傳。你的目標是將 vector container 裡面的每一個物件的面積通通加總。

int main(){

...

... = generateData();

...

}

你想要用多形(polymorphism)來完成這件事情。請撰寫未完成的 main()以及你需要

對 Rectangle, Circle 兩個 class 的原始程式碼做任何的修改。(25 


你可以利用多形(polymorphism)的概念,編寫一個 C++ 程式,使得你的 `main()` 函式能夠處理 `Rectangle` 和 `Circle` 物件的 vector,並計算它們的面積總和。以下是完成這項任務的程式碼:


首先,你的 `Rectangle` 和 `Circle` 類別的程式碼保持不變:


```cpp

class Rectangle {

private:

    float width;

    float height;


public:

    Rectangle(float width, float height) : width(width), height(height) { }

    float getArea() const { return width * height; }

};


class Circle {

private:

    float radius;


public:

    Circle(float radius): radius(radius) { }

    float getArea() const { return 3.14159f * radius * radius; }

};

```


接下來,你的 `generateData()` 函式可以修改為以下的形式,它會隨機產生 `Rectangle` 和 `Circle` 物件,然後放入 vector 中:


```cpp

#include <iostream>

#include <vector>

#include <ctime>

#include <cstdlib>


std::vector<Shape*> generateData(int numShapes) {

    std::vector<Shape*> shapes;


    for (int i = 0; i < numShapes; ++i) {

        if (rand() % 2 == 0) {

            float width = static_cast<float>(rand() % 10 + 1);

            float height = static_cast<float>(rand() % 10 + 1);

            shapes.push_back(new Rectangle(width, height));

        } else {

            float radius = static_cast<float>(rand() % 10 + 1);

            shapes.push_back(new Circle(radius));

        }

    }


    return shapes;

}

```


在你的 `main()` 函式中,你可以使用多形來計算所有圖形的總面積,而不需要關心它們是 `Rectangle` 還是 `Circle`:


```cpp

int main() {

    // 初始化亂數種子

    std::srand(static_cast<unsigned>(std::time(nullptr)));


    std::vector<Shape*> shapes = generateData(10); // 產生 10 個隨機圖形


    float totalArea = 0.0f;

    for (Shape* shape : shapes) {

        totalArea += shape->getArea(); // 多形呼叫適當的 getArea() 函式

    }


    std::cout << "Total area: " << totalArea << std::endl;


    // 釋放記憶體

    for (Shape* shape : shapes) {

        delete shape;

    }


    return 0;

}

```


這樣,你的 `main()` 函式可以處理包含 `Rectangle` 和 `Circle` 物件的 vector,並計算它們的總面積,而不需要在乎特定的類型。


Comments

Popular posts from this blog

How to write data into a excel file using vbscript

Format date as yyyy-mm-dd using vbscript