C++ auto类型说明符

2020-01-06 14:50:14刘景俊


auto x = 1, *y = &x, **z = &y; // Resolves to int.
auto a(2.01), *b (&a);     // Resolves to double.
auto c = 'a', *d(&c);     // Resolves to char.
auto m = 1, &n = m;      // Resolves to int.

此代码片段使用条件运算符 (?:) 将变量 x 声明为值为 200 的整数:


int v1 = 100, v2 = 200;
auto x = v1 > v2 ? v1 : v2;

下面的代码片段将变量 x 初始化为类型 int,将变量 y初始化对类型 const int 的引用,将变量 fp 初始化为指向返回类型 int 的函数的指针。


int f(int x) { return x; }
int main()
{
  auto x = f(0);
  const auto & y = f(1);
  int (*p)(int x);
  p = f;
  auto fp = p;
  //...
}