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

更新日期: 12-Mar-2020

148 人瀏覽

開啟你的職業生涯

透過完成該課程,獲得認證

開始
廣告