首页 文章资讯内容详情

C ++中的类型推断(自动和decltype)

2026-06-05 1 花语

在本教程中,我们将讨论一个程序来理解C++中的类型干扰(自动和decltype)。

如果使用auto关键字,则变量的类型是根据其初始值设定项的类型定义的。进一步使用decltype,它使您可以从被调用的元素中提取变量的类型。

自动类型

示例

#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

定义类型

示例

#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