auto声明的变量必须在定义的时候初始化。(要不你咋推导)
初始化的右值可以是具体数值,也可以是表达式和函数的返回值等。
#include<iostream>
using namespace std;
string func() {
return "wangtianhao";
}
int main() {
auto a = 3+1; cout << "a=" << a << endl;
auto b = 3.3+a; cout << "b=" << b << endl;
auto c = "zhengxu"; cout << "c=" << c << endl;
auto d = func(); cout << "d=" << d << endl;
return 0;
}
auto不能作为函数的形参类型;
auto不能直接声明数组
auto不能定义类的非静态成员变量;
不要滥用auto。
主要用于以下场景:
1.代替冗长复杂的变量声明;
#include <iostream>
using namespace std;
double func(int a, double b, const char *c, float d, short e, long f) {
cout << a << b << c << d << e << f << endl;
return 5.5;
}
int main() {
double (*pf)(int, double, const char *, float, short, long); //声明函数指针
pf = func;
pf(1, 2, "钟佳铭", 3, 4, 5);
return 0;
}
函数指针声明很麻烦,用auto代替:
#include <iostream>
using namespace std;
double func(int a, double b, const char *c, float d, short e, long f) {
cout << a << b << c << d << e << f << endl;
return 5.5;
}
int main() {
double (*pf)(int, double, const char *, float, short, long); //声明函数指针
pf = func;
pf(1, 2, "钟佳铭", 3, 4, 5);
return 0;
}
代替后:
#include <iostream>
using namespace std;
double func(int a, double b, const char *c, float d, short e, long f) {
cout << a << b << c << d << e << f << endl;
return 5.5;
}
int main() {
auto pf1 = func;
pf1(1, 2, "钟佳铭", 3, 4, 5);
return 0;
}