基於給定的 Rect 結構體和 InitRect 初始化函數,補全求周長 getround 和面積 getarea 操作。
#include <iostream>
using namespace std;
struct Rect {
double length;
double width;
};
// 聲明
void InitRect(Rect &R, double l, double w);
double getarea(Rect &R);
double getround(Rect &R);
int main() {
Rect my_rect;
double Length, Width, Circ, Area;
cout << "Input length, width: " << endl;
cin >> Length >> Width;
InitRect(my_rect, Length, Width);
Area = getarea(my_rect);
Circ = getround(my_rect);
cout << "Area = " << Area << endl;
cout << "Circumference = " << Circ << endl;
return 0;
}
// 初始化
void InitRect(Rect &R, double l, double w) {
R.length = l;
R.width = w;
}
// 面積
double getarea(Rect &R) {
return R.length * R.width;
}
// 周長
double getround(Rect &R) {
return 2 * (R.length + R.width);
}
Rect &R 避免結構體拷貝,且允許函數修改原對象(初始化時需要)。getarea/getround 動詞開頭,語義清晰。bool isSquare(Rect &R) 判斷是否為正方形。operator<< 直接輸出矩形信息:cout << my_rect;。class 封裝,私有成員,提供構造函數、getter/setter。結構體
struct默認成員public,類class默認private;繼承默認訪問權限同理。本質上無區別,語義上struct傾向純數據聚合,class傾向行為封裝。