自动推导类型

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值