萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ 派生類實戰:從 Point 到 Circle 的繼承與多態設計

需求分析

基於現有的 Point 類(二維坐標點),設計派生類 Circle(圓),新增半徑屬性,並實現計算圓周長與面積的功能。這是一個經典的「is-a」關係建模案例。

基類 Point 設計

#ifndef POINT_H
#define POINT_H

class Point {
private:
    float x, y;

public:
    // 構造函數
    Point() : x(0), y(0) {}
    Point(float a, float b) : x(a), y(b) {}
    Point(const Point& ob) : x(ob.x), y(ob.y) {}

    // 操作接口
    void setPoint(float a, float b);
    float getX() const;
    float getY() const;
    void move(float a, float b);       // 非 const 版本:修改自身
    void move(float a, float b) const; // const 版本:邏輯錯誤,見下文
};

#endif

關鍵點:

  • 提供默認、參數、拷貝構造函數,確保對象正確初始化。
  • 坐標封裝為 private,通過 getX()/getY() 只讀訪問。
  • move 重載:非常量版本修改坐標;常量版本邏輯上不應修改成員,實現時需謹慎(示例中註釋掉了常量版本的修改行)。

派生類 Circle 實現

#ifndef CIRCLE_H
#define CIRCLE_H
#include "Point.h"

#define PI 3.1415926f

class Circle : public Point {
private:
    float r; // 半徑

public:
    // 構造函數鏈:調用基類構造函數初始化圓心
    Circle(float a, float b, float c) : Point(a, b), r(c) {}

    void setRadius(float a) { r = a; }
    float getRadius() const { return r; }

    // 計算並輸出周長與面積
    void circumference() const;
    void area() const;
};

#endif

成員函數定義

// Point.cpp
#include "Point.h"
#include 
using namespace std;

void Point::setPoint(float a, float b) { x = a; y = b; }
float Point::getX() const { return x; }
float Point::getY() const { return y; }
void Point::move(float a, float b) { x += a; y += b; }
void Point::move(float a, float b) const { /* 邏輯上不應修改,留空或拋出異常 */ }

// Circle.cpp
#include "Circle.h"
#include 
using namespace std;

void Circle::circumference() const {
    float c = 2 * PI * r;
    cout << "圓周長 = " << c << endl;
}

void Circle::area() const {
    float s = PI * r * r;
    cout << "圓面積 = " << s << endl;
}

主程序測試

#include "Circle.h"
#include 
using namespace std;

int main() {
    Circle c(1.2f, 2.0f, 3.0f); // 圓心(1.2, 2.0),半徑3.0
    cout << "圓心座標: (" << c.getX() << ", " << c.getY() << ")" << endl;
    cout << "半徑: " << c.getRadius() << endl;
    c.circumference();
    c.area();
    return 0;
}

設計要點總結

  1. 繼承方式:public 繼承保留基類接口語義,Circle 確實是一種 Point(圓心)。
  2. 構造函數鏈:派生類構造函數必須在初始化列表中調用基類構造函數。
  3. Const 正確性:查詢類函數(getX、circumference)均標記 const,保證不修改對象狀態。
  4. 封裝性:半徑 r 為私有,提供存取器控制訪問。

此例展示了 C++ 面向對象建模的核心思想:通過繼承復用代碼,通過封裝保護數據,通過多態(此處為接口復用)實現擴展。

copyright © 萬盛學電腦網 all rights reserved