指標:記憶體地址的直接操作
指標儲存變數的記憶體位址。宣告形式 型別* 名稱,解參考用 *ptr,取址用 &var。
基本操作
int var = 20;
int* ip = &var; // ip 指向 var
cout << *ip; // 20,透過指標讀取值
*ip = 30; // 修改 var 為 30
指標類型與大小
- 所有指標大小相同(32 位元 4 bytes,64 位元 8 bytes),儲存的是位址。
- 類型決定解參考時讀寫多少位元組與指標運算步長(
ptr+1 前進 sizeof(型別) 位元組)。
引用:變數的別名
引用是已存在變數的別名,宣告 型別& 別名 = 原變數。初始化後不可重新綁定,無空引用。
引用 vs 指標三大差異
| 特性 | 引用 | 指標 |
| 可為空 | 否 | 是 |
| 可重新綁定 | 否 | 是 |
| 初始化時機 | 宣告時必須 | 隨時 |
常見用途
- 函數參數:
void swap(int& a, int& b) 避免拷貝、可修改實參
- 返回值:
int& func() 返回左值(如運算子 [])
- 範圍 for:
for (auto& x : vec) 避免拷貝
日期與時間:<ctime> 傳統 API
C++ 繼承 C 的時間設施,核心型別:
time_t:自 1970-01-01 秒數
tm 結構:分解時間(年、月、日、時、分、秒、週、年內天、夏令時)
關鍵函數
time_t now = time(nullptr); // 目前時間戳
tm* local = localtime(&now); // 轉本地時間結構
tm* gmt = gmtime(&now); // 轉 UTC
char* str = asctime(local); // 格式化字串
time_t t = mktime(local); // 結構轉時間戳
double diff = difftime(t2, t1); // 秒差
格式化輸出 strftime
char buf[80];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", local);
cout << buf; // 2024-01-15 14:30:00
I/O 流:<iostream> 體系
C++ 以流統一處理輸入輸出,核心物件:
| 物件 | 類別 | 用途 | 緩衝 |
cin | istream | 標準輸入 | 緩衝 |
cout | ostream | 標準輸出 | 緩衝 |
cerr | ostream | 標準錯誤 | 無緩衝,立即輸出 |
clog | ostream | 標準日誌 | 緩衝 |
常用操作
// 輸出
cout << "Hello" << ' ' << 123 << endl; // endl 換行並刷新緩衝
// 輸入
string name; int age;
cin >> name >> age; // 連續提取,遇空白停止
// 讀整行
getline(cin, name); // 含空白
// 忽略字元
cin.ignore(); // 忽略 1 字元
cin.ignore(100, '\n'); // 忽略至換行或 100 字元
結構體:異質資料聚合
struct 定義使用者自訂型別,可包含不同型別成員。
定義與實例化
struct Book {
char title[50];
char author[50];
int id;
};
Book b1; // 預設建構
Book b2 = {"C++ Primer", "Lippman", 101}; // 聚合初始化
成員存取
strcpy(b1.title, "Effective C++");
b1.id = 102;
cout << b1.title << ' ' << b1.id;
結構體做函數參數
void printBook(const Book& b) { // 傳參考避免拷貝
cout << b.title << ' ' << b.author << ' ' << b.id << endl;
}
完整範例:通訊錄原型
#include <iostream>
#include <cstring>
#include <ctime>
using namespace std;
struct Contact {
char name[32];
char phone[16];
time_t created;
};
void addContact(Contact& c) {
cout << "Name: "; cin.getline(c.name, 32);
cout << "Phone: "; cin.getline(c.phone, 16);
c.created = time(nullptr);
}
void showContact(const Contact& c) {
char buf[80];
strftime(buf, sizeof(buf), "%F %T", localtime(&c.created));
cout << c.name << " | " << c.phone << " | " << buf << endl;
}
int main() {
Contact c;
addContact(c);
showContact(c);
return 0;
}
核心心法
- 指標:誰擁有記憶體?誰負責釋放? 現代 C++ 用智慧指標/容器替代裸指標。
- 引用:首選函數參數/返回值,只在需「可空」或「重新綁定」時用指標。
- 時間:
chrono (C++11) 取代 ctime,型別安全、精度高、支援字面量。
- I/O:錯誤用
cerr、日誌用 clog、一般輸出用 cout。
- 結構體:資料導向設計,搭配
const& 參數、std::string 替代字元陣列更安全。
- 上一篇文章: C++ STL 容器精講:deque 雙端佇列完整操作指南
- 下一篇文章: C++ 入門基石:語言特性、安裝編譯、資料型別、運算符與陣列
Copyright ©
程式碼之家 All Rights Reserved