C++的typedef及using可設定資料型別的別名(alias)。
typedef
typedef源於C語言,設定形別別名的語法如下:
type- 既有型別。alias- 別名
typedef type alias
例如原本宣告一個長整數的語法為long int,使用typedef貨using給予該形態一個別名,語法為。
main.cpp
#include <iostream>
using namespace std;
int main() {
typedef long int longint; // 設定long int型態的別名為longint
longint id = 1; // 使用別名型別
cout << sizeof(longint) << endl; // 8
cout << id << endl; // 1
return 0;
}
using
C++11開始可使用using設定資料型別的別名的語法如下:
type- 既有型別。alias- 別名
using alias = type
範例。
#include <iostream>
using namespace std;
int main() {
using longint = long int; // 設定long int型態的別名為longint
longint id = 1; // 使用別名型別
cout << sizeof(longint) << endl; // 8
cout << id << endl; // 1
return 0;
}
typedef及using作用幾乎相同但仍有差別,除了語法差異外,typedef無法以模板(template)為別名。且using的可讀性較佳所以建議使用。
定義型別別名的好處是可以讓型別的語義及用途更清楚,雖然也可透過良好的變數命名來達成。
沒有留言:
張貼留言