📌 引用就是變數的一個「別名」
就像幫變數取了另一個名字
int &ref = a;
ref
和 a
指向同一個值#include <iostream>
using namespace std;
int main()
{
int a = 10;
int &ref = a;
ref = 20;
cout << "a = " << a << endl;
return 0;
}
📌 const
表示「常數」,不能被修改
搭配引用使用時,可以保護資料不被改動
const int &ref = a;
#include <iostream>
using namespace std;
void printa(const int &x)
{
cout << "a = " << x << endl;
}
int main()
{
int a = 30;
printa(a);
return 0;
}
#include <iostream>
using namespace std;
#define PI 3.14
int main()
{
cout << PI << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
const double PI = 3.14;
cout << PI << endl;
return 0;
}
#define |
const |
|
---|---|---|
類型檢查 | 沒有 | 有 |
範圍 | 全域 | 有作用域限制 |
複雜型別 | 不行 | 可以(int、double、struct…) |
編譯檢查 | 不會報錯 | 編譯器會檢查 |
📌 #define
是前處理器巨集
編譯前就會直接進行文字替換
沒有型別與作用域概念
📌 const
,有型別檢查與作用域限制
引用讓程式更直觀
因為它就像變數的別名
const
可以進一步保護資料
讓函式能安全地讀取變數
而不會誤修改