cmelove 2021-04-05 20:44 采纳率: 100%
浏览 154
已采纳

C++ 11 新特性中的auto类型转换问题

#include <iostream>
#include <string>
using namespace std;

// 1. 如果 目标表达式    是指针或者引用            保留        源表达式的限定符 (const volatile)
// 2. 如果 目标表达式    不是是指针或者引用     抛弃        源表达式的限定符 (const volatile)

int main(void)
{
    int tmp = 250;                        // int
    const auto a1 = tmp;            // const int
    auto a2 = a1;                        // int                    -- a2 不是指针或者引用 卸掉 const
    const auto& a3 = tmp;            // const int &    -- a3 是指针或者引用 保留 const
    auto& a4 = a3;                        // const int &    -- a4 是指针或者引用 保留 const
    auto* pt4 = &a1;                    // const int *        -- pt4 是指针或者引用 保留 const
    auto pt5 = pt4;                        // const int *       --auto pt5 不是 指针或者引用 应该卸载 const 但为什么 还是 const int * 类型???

    system("pause");
    return EXIT_SUCCESS;
}

  • 写回答

3条回答 默认 最新

  • 神奇小七 2021-04-06 01:31
    关注

    auto一般会忽略掉顶层的const,同时底层const则会保留下来(C++ primer)。

    pt4包含了const的底层所以被复制了,所以常量指针是会被复制的。

    你可以试以下指针常量int * const p = &tmp;会有更多的收获。

     

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c51单片机控制步进电机
  • ¥20 Visual studio无法检测到设备
  • ¥15 为什么我通过html绘制的SVG折线图插入到word中坐标轴不显示出来
  • ¥30 vue 页面窗口放大或者缩小元素会变化
  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 多目标优化算法在与其他算法数据对比结果判断
  • ¥15 CPTN和EAST,主干网络是VGG16,请问在ICDAR2015数据集上训练之后,CPTN和EAST模型的大小为多少