基於現有的 Point 類(二維坐標點),設計派生類 Circle(圓),新增半徑屬性,並實現計算圓周長與面積的功能。這是一個經典的「is-a」關係建模案例。
#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 重載:非常量版本修改坐標;常量版本邏輯上不應修改成員,實現時需謹慎(示例中註釋掉了常量版本的修改行)。#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;
}
public 繼承保留基類接口語義,Circle 確實是一種 Point(圓心)。getX、circumference)均標記 const,保證不修改對象狀態。r 為私有,提供存取器控制訪問。此例展示了 C++ 面向對象建模的核心思想:通過繼承復用代碼,通過封裝保護數據,通過多態(此處為接口復用)實現擴展。