C++教程之autokeyword的使用

一、autokeyword的前世

从C语言開始,autokeyword就被当作是一个变量的存储类型修饰符,表示自己主动变量(局部变量)。它不能被单独使用,否则编译器会给出警告。

#include <stdio.h>

int main()
{
        int a = 123;
        auto int b = 234;
        auto c = 345;

        printf("a = %d, b = %d, c = %d
", a, b, c);
        return 0;
}

编译执行结果:

$ gcc main.c
main.c:7:7: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
        auto c = 345;
        ~~~~ ^
1 warning generated.
$ ./a.out 
a = 123, b = 234, c = 345

二、autokeyword的今生

C++ 11标准中,加入了新的类型推导特性,考虑到autokeyword非常少使用,就给它又一次赋予了功能——申明类型由编译器推导的变量。

C++ 11中。使用auto定义的变量不能使用其他类型修饰符修饰,该变量的类型由编译器依据初始化数据自己主动确定。auto类型的变量必须进行初始化。

#include <iostream>

int main()
{
        int a = 21;
        auto b = a;

        //typeid能够获取变量或者数据类型的名字
        std::cout << typeid(b).name() << std::endl;

        return 0;
}

1 .使用C++ 98标准进行编译,会出现警告:

$ clang++ main.cpp -std=c++98
main.cpp:6:2: warning: 'auto' type specifier is a C++11 extension
      [-Wc++11-extensions]
        auto b = a;
        ^
1 warning generated.
$ ./a.out 
i                   #输出结果为整数类型

改用C++ 11进行编译:

$ clang++ main.cpp -std=c++11
$ ./a.out 
i

2 .可是假设还是将auto作为存储类型修饰符使用,则在C++ 11标准下会出现警告:

#include <iostream>

int main()
{
        int a = 21;
        auto int b = a;

        //typeid能够获取变量或者数据类型的名字
        std::cout << typeid(b).name() << std::endl;

        return 0;
}

使用C++ 98编译:

$ clang++ main.cpp -std=c++98
$ ./a.out 
i

改用C++ 11编译,出现警告,不再同意作为存储类型修饰符使用:

$ clang++ main.cpp -std=c++11
main.cpp:6:2: warning: 'auto' storage class specifier is not permitted in C++11,
      and will not be supported in future releases [-Wauto-storage-class]
        auto int b;
        ^~~~~
1 warning generated.

3 .必需要对auto类型的变量进行初始化,C++ 98中不能单独使用auto定义变量。

$ clang++ main.cpp -std=c++98
main.cpp:6:2: warning: 'auto' type specifier is a C++11 extension
      [-Wc++11-extensions]
        auto b;
        ^
main.cpp:6:7: error: declaration of variable 'b' with type 'auto' requires an
      initializer
        auto b;
             ^
1 warning and 1 error generated.
$ clang++ main.cpp 
main.cpp:6:2: warning: 'auto' type specifier is a C++11 extension
      [-Wc++11-extensions]
        auto b;
        ^
main.cpp:6:7: error: declaration of variable 'b' with type 'auto' requires an
      initializer
        auto b;
             ^
1 warning and 1 error generated.

三、扩展

在C++中还能使用decltype来获取变量或者表达式的类型并用来定义新的变量。

#include <iostream>

int main()
{
        int a = 21;
        decltype(a) b;

        std::cout << typeid(b).name() << std::endl;

        return 0;
}

编译执行结果:

$ clang++ main.cpp -std=c++98
$ ./a.out 
i
$ clang++ main.cpp -std=c++11
$ ./a.out 
i

须要注意的是该标准仅仅是改变了C++中auto的使用方法。可是并没有影响auto在C语言中的使用!

本文档由长沙戴维营教育整理。

原文地址:https://www.cnblogs.com/zsychanpin/p/6802542.html