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