C++中的型別推斷(auto和decltype)
本教程中,我們將討論一個程式,以瞭解 C++ 中的型別推斷(auto 和 decltype)。
對於 auto 關鍵字來說,該變數的型別由其初始化程式的型別定義。此外,使用 decltype 可從所呼叫的元素中提取變數型別。
auto 型別
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
auto x = 4;
auto y = 3.37;
auto ptr = &x;
cout << typeid(x).name() << endl
<< typeid(y).name() << endl
<< typeid(ptr).name() << endl;
return 0;
}輸出
i d Pi
decl 型別
示例
#include <bits/stdc++.h>
using namespace std;
int fun1() { return 10; }
char fun2() { return 'g'; }
int main(){
decltype(fun1()) x;
decltype(fun2()) y;
cout << typeid(x).name() << endl;
cout << typeid(y).name() << endl;
return 0;
}輸出
i c
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP