以「座標輸入與倒三角列印」為例,對比 C 語言「結構體 + 函式」與 C++「類別 + 封裝 + 內聯函式」的程式設計風格差異,並延伸展示 Java 實作,幫助跨語言開發者快速掌握 C++ 核心觀念轉換。
#include <stdio.h> #include <stdlib.h>
struct Location { int x, y; } location; // 全域實例
void print(int x, int y); // 前向宣告
int main() {
printf("輸入X: "); scanf("%d", &x); location.x = x;
printf("輸入Y: "); scanf("%d", &y); location.y = y;
printf("X=%d Y=%d\n", location.x, location.y);
print(x, y);
return EXIT_SUCCESS;
}
void print(int x, int y) {
for (int i = 0; i < y; i++) {
printf("%d\t", i+1);
for (int j = i; j < x; j++) printf("* ");
printf("\n");
}
}
特徵:資料(結構體)與行為(函式)分離、全域變數可見、手動前向宣告、scanf/printf 格式化字串。
#include <iostream>
using namespace std;
class Location {
int x, y; // private 預設
public:
Location() {}
Location(int x, int y) : x(x), y(y) {} // 初始化列表
int getX() const { return x; }
void setX(int x) { this->x = x; }
int getY() const { return y; }
void setY(int y) { this->y = y; }
};
inline void print(int x, int y) { // 建議內聯
for (int i = 0; i < y; i++) {
cout << i+1 << "\t";
for (int j = i; j < x; j++) cout << "* ";
cout << endl;
}
}
int main() {
Location loc;
int x, y;
cout << "輸入X: "; cin >> x; loc.setX(x);
cout << "輸入Y: "; cin >> y; loc.setY(y);
cout << "X=" << loc.getX() << " Y=" << loc.getY() << endl;
print(x, y);
return 0;
}
| 維度 | C (結構體) | C++ (類別) |
|---|---|---|
| 資料隱藏 | 無(全部公開) | private + get/set |
| 資料與行為 | 分離 | 封裝於類別內 |
| 建構/初始化 | 手動賦值 | 建構函式 + 初始化列表 |
| 指標語法 | 無 | this->member 明確指標語意 |
| I/O | scanf/printf | cin/cout 型別安全、可擴充 |
| 函式優化 | 無 | inline 建議編譯器展開 |
| 命名空間 | 全域 | namespace std |
// 類別內宣告
class Location {
int x, y;
public:
Location(int x, int y);
int getX() const;
void setX(int x);
// ...
};
// 類別外實作
Location::Location(int x, int y) : x(x), y(y) {}
int Location::getX() const { return x; }
void Location::setX(int x) { this->x = x; }
適用於大型專案分離介面與實作、減少編譯相依。
import javax.swing.JOptionPane;
public class Location {
private int x, y;
public int getX() { return x; }
public void setX(int x) { this.x = x; }
// ...
public static void main(String[] args) {
Location loc = new Location();
int x = Integer.parseInt(JOptionPane.showInputDialog("輸入X:"));
int y = Integer.parseInt(JOptionPane.showInputDialog("輸入Y:"));
loc.setX(x); loc.setY(y);
loc.print(x, y);
}
public void print(int x, int y) { /* 同 C++ 邏輯 */ }
}
觀察:Java 強制類別即檔案、無 this->(用 this.)、System.out 替代 cout、例外處理機制完善。
輸入X: 9
輸入Y: 9
X=9 Y=9
1 * * * * * * * * *
2 * * * * * * * *
3 * * * * * * *
4 * * * * *
5 * * * *
6 * * *
7 * *
8 *
9 *
cin/cout 雖不如 Java 直觀,但支援運算子重載擴充,型別安全優於 printf。inline、初始化列表、const 成員函式,寫出高效且安全的 C++ 代碼。此對比為後續學習繼承、多型、STL、範本等進階主題奠定堅實基礎。