栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ auto声明

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ auto声明

auto类型推导: auto 定义的变量,可以根据初始化的值,在编译时推导出变量名的类型。

int main()
{
	auto x=5;//ok x是int类型
	auto pi = new auto(1); // ok pi 被推导为int *;
	const auto *xp = &x, u = 6; // ok xp是const int*类型,u是const int类型
	static auto dx = 0.0;  // ok dx是double类型
	auto int b;   // error C11中auto不再表示存储类型指示符
	auto s;  // error没有初始化值auto无法推导出s的类型
}

使用auto声明的变量必须要有初始化值,以让编译器推断出它的实际类型,并在编译时将auto 占位符替换为真正的数据类型。

auto作为函数形参
void func(auto x)
{
	cout << sizeof(x) << end7 ;
	cout << typeid(x) . name() < << end1 ;
}
int main()
{
	int a=10;
	int ar[]={12 ,23,34,45,56};
	fun(a);
	fun(ar);
}
void funr(auto &x)
{
    cout << sizeof(x) << end1;
	cout << typeid(x) . name() << end1;
}
int main()
{
    int a=10;
	int ar[]={12 ,23,34,45,56};
	fun(a) ;
	fun(ar);
}

auto作为返回值推导返回值类型

template
T my_max(T a,T b)
{
    return a>b?a:b;
}
int main()
{
	auto x = my_max(12,23) ;
	auto y = my_max('a','b');
	cout< 

auto限制

struct Foo
{
	auto value = 0;            //error: auto不能用于非静态成员变量
	static const int num = 10; //OK: num -> static const int;
};
int main()
{
	int ar[10]={0};
	auto br = ar;           //ok br->int*
	auto cr[10] = ar        // error : auto 无法定义数组
	auto dr[5]={1,2,3,4,5}; // error : auto 无法定义数组
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/870074.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号