c++ auto关键字

一些关于C++的出版物写到:我们经常会用到一些赋值操作,例如int a=6,前提是我们知道变量的类型。-----但我们经常不知道变量的类型,因此就要允许c++编译器帮我们判断变量类型,由此auto变量应孕而生

  • 一般用法
#include<iostream>
using namespace std;
int main()
{
    auto i = 888;
    auto coachname = "陈培昌";
    int myarray[5] = {7,8,5,48,32};
    cout << i<<endl;
    cout << coachname << endl;
}

输出结果:

  •  一些应用场景:循环打印数组元素
#include<iostream>
using namespace std;
int main()
{
    
    int myarray[5] = {7,8,5,48,32};
    for (auto wenwa : myarray)
    {
        cout << wenwa << endl;
    }
    return 0;
}

输出结果:

  •  一些使用问题----批量赋值的时候,尽量保持变量类型一致,否则报错
#include<iostream>
using namespace std;
int main()
{
    auto name = "付高峰", i = 666;
    return 0;
}

输出结果:

  • 更改
#include<iostream>
using namespace std;
int main()
{
    auto name = "付高峰", i = "魏锐";
    return 0;
}
原文地址:https://www.cnblogs.com/saintdingspage/p/12187842.html