auto有时不auto

反直觉C++🔥, 👏欢迎github star

auto有时不auto

c++ 复制代码
#include <iostream>

int main() {
   int a = 1;
   int& b = a;
   auto c = a;
   auto d = b;
   auto& e = b;
  
   std::cout << "a:" << a << " b:" << b << " c:" << c << " d:" << d << " e:" << e << std::endl;
   
   a = 10;
   
   std::cout << "a:" << a << " b:" << b << " c:" << c << " d:" << d << " e:" << e << std::endl;
}

输出

c++ 复制代码
a:1 b:1 c:1 d:1 e:1
a:10 b:10 c:1 d:1 e:10

变量a是int类型,变量b是int&类型,变量c是int类型(同a),变量d是int类型(与b不同),变量e是int类型(同b),auto没有把d推导为和b相同的类型,有点反直觉。

奇怪的知识增加了

如果希望推演出来的auto类型为引用(左值引用),需要明确指出,就像变量e定义的那样:

c++ 复制代码
auto& e = b;

如果希望推演出来的auto类型携带const,也需要明确指出:

c++ 复制代码
const auto ca = a;  // ca是const int
相关推荐
哇哈哈20211 天前
信号量和信号
linux·c++
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马1 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝1 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc1 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼1 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛
yyjtx1 天前
DHU上机打卡D31
开发语言·c++·算法
czxyvX1 天前
020-C++之unordered容器
数据结构·c++
会编程的土豆1 天前
2.25 做题
数据结构·c++·算法