阿摩線上測驗 登入

申論題資訊

試卷:101年 - 101年警察人員、101年一般警察人員、101年交通事業鐵路人員考員級_資訊處理#33788
科目:程式設計
年份:101年
排序:0

申論題內容

四、請使用 C++或 Java 撰寫三個類別(class):shape(形狀)、circle(圓形)與 rectangle(矩形),其中 shape 為抽象類別(abstract class),而 circle 與 rectangle 為 衍生類別(derived class),均繼承 shape。請在 shape 中定義兩個介面(interface), 分別作為運算週長(circumference)與面積(area)的介面,並在 circle 與 rectangle 中分別實作其功能。(26 分)

詳解 (共 1 筆)

詳解 提供者:114年高考上榜
 
class Shape {
public:
    virtual double area() = 0; // 面積介面
    virtual double circumference() = 0; // 週長介面
};
 
class Circle : public Shape {
private:
    double radius;
public:
    Circle(double r) { radius = r; }
    double area() { return 3.14 * radius * radius; } // 圓形面積公式
    double circumference() { return 2 * 3.14 * radius; } // 圓形週長公式
};
 
class Rectangle : public Shape {
private:
    double length;
    double width;
public:
    Rectangle(double l, double w) { length = l; width = w; }
    double area() { return length * width; } // 矩形面積公式
    double circumference() { return 2 * (length + width); } // 矩形週長公式
};
 
int main() {
    Circle circle(5);
    Rectangle rectangle(4, 6);
    
    cout << "圓形面積: " << circle.area() << endl;
    cout << "圓形週長: " << circle.circumference() << endl;
    cout << "矩形面積: " << rectangle.area() << endl;
    cout << "矩形週長: " << rectangle.circumference() << endl;
    
    return 0;
}