auto使用

C++11引入了类型说明符auto,它给我们带来了方便,但有时也会因为使用不当而造成错误。
说明:

  1. auto只能用于识别类型。如int,string,类类型等
  2. auto不能代替引用&

auto与指针,引用的关系

9 #include <iostream>
 10                                                                                                                                                                                          
 11 int x;
 12 int *y = &x;
 13 
 14 int func()
 15 {
 16    std::cout <<__func__<<std::endl;
 17 }  
 18 
 19 int& foo()
 20 {
 21    std::cout <<__func__<<std::endl;
 22 }  
 23 
 24 
 25 
 26 int main()
 27 {
 28     auto *a = &x;        //int*
 29     auto &b = x;        //int&
 30     auto c = y;            //int*
 31     auto *d = y;          //int*
 32     
 33     auto *e = &func();      //编译失败,指针不能指向一个临时的变量(纯右值)
 34     auto &f = func();         //编译失败,非const的左值引用不能喝一个临时变量(纯右值)绑定
 35     auto g = foo();           //int
 36     auto &h = foo();       //int&
 37     
 38     return 0;
 39 }   

输出:

[xqs@localhost ~/src]g++ -std=gnu++11 test.cpp -o test -w
test.cpp: 在函数‘int main()’中:
test.cpp:33:18: 错误:单目‘&’的操作数必须是左值
  auto *e = &func();//编译失败,指针不能指向一个临时的变量(纯右值)
test.cpp:34:17: 错误:用类型为‘int’的右值初始化类型为‘int&’的非常量引用无效
  auto &f = func();//编译失败,非const的左值引用不能与一个临时变量(纯右值)绑定
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值