定義長方柱類 Bulk,構造函數支持默認參數,計算體積、表面積,輸出信息。創建 5 個對象數組,部分用構造函數初始化,部分用輸入函數賦值,最後遍歷輸出所有對象的體積和表面積。
length, width, height。Bulk(double l=1, double w=1, double h=1)。volume():返回 l*w*h。area():返回 2*(l*w + l*h + w*h)。get_value():鍵盤輸入三維尺寸。out_put():輸出尺寸、面積、體積。#include <iostream>
#include <cmath>
using namespace std;
class Bulk {
public:
Bulk(double l=1, double w=1, double h=1) : length(l), width(w), height(h) {}
double volume() { return length * width * height; }
double area() { return 2 * (length*width + length*height + width*height); }
void get_value() {
cout << "請輸入長寬高:" << endl;
cin >> length >> width >> height;
}
void out_put() {
cout << "長方柱尺寸:" << length << " " << width << " " << height << endl;
cout << "表面積:" << area() << " 體積:" << volume() << endl;
}
private:
double length, width, height;
};
int main() {
Bulk b[5] = { Bulk(2.3,4.5,6.7), Bulk(1.5,3.4), Bulk(10.5) }; // 後兩個用默認值
b[4].get_value(); // 第5個對象鍵盤輸入
for (int i = 0; i < 5; i++) {
cout << "第 " << i+1 << " 個:";
b[i].out_put();
}
return 0;
}

逐漸熟悉了類的構造函數重載、默認參數、對象數組初始化及成員函數調用。注意 Bulk(1.5,3.4) 只傳兩參數時,第三參數取默認值 1;Bulk(10.5) 只傳一參數時,後兩者均為 1。這種靈活的初始化方式很實用。