C++auto 、范围for、nullptr

>>:流提取

std::cin>>i;//键盘上输入的东西,输入到变量i中

<<:流插入

std::cout<<"hello world"<<endl;//将数据打印在控制台上

auto关键词

早期的C语言使用它是:auto修饰的变量,是具有自动存储的局部变量。

//.C
auto int a;

后来发现这个根本无用,

使用在C++11中,重新定义auto的使用

int a=10;
int b=20;
// 自动推导c的类型:int;
auto c=a;
// 自动推导d的类型:char;
auto d='a';

ps:小知识

typeid(a).name()//获取数据类型

int a=10;
auto c=a;//自动获取数据类型
std::cout<<typeid(c).name()<<std::endl;

打印:int


但是这样的,没有意义,auto和float,写的差不了多少,主要是这样用

    //迭代器
    std::map<std::string, std::string> dct = { {"sort","排序"}, {"Insert"," 插入"} };
    std::map<std::string, std::string> it = dct.begin();
    //it前面太长了,可以使用auto自动识别std::map<std::string, std::string>这样类型
    //改为
    //根据右边的值,自动推导it应该的类型
    auto it=dct.begin();

auto的小问题

int main()
{
    int x=10;
    auto a=x;//a  int
    auto b=&x;//b  int*
    auto&c=x;//c  int-c是x的引用
    auto c=x;//c  int-c是x的拷贝

推出不带const属性

如果想让rg带const属性呢?

在auto前自己加const关键子 ;

auto不能做参数的

int add(auto a,auto b);//编译失败,编译器无法对a,b类型进行推导

auto不能为初始化

auto x;//编译失败,编译器不知道x的类型,无法进行推导

也不能定义数组

auto a[]={1,2,3,4};//编译失败,编译器设计人员才知道原因。 

范围for循环

int main()
{
    int array[] = { 1,2,3,4,5,6 };
    for (int i = 0; i < sizeof(array) / sizeof(array[0]); i++)
    {
        std::cout << array[i] ;
    }
//C++11.范围for循环
    for (auto e : array)
    {
        std::cout << e;
    }
}

语法糖:自动取数组array的每个元素赋值给e,自动判断遍历结束。auto可改为int

改变数据

    //使用引用,改变数组里的所有值,e的生命周期只有一次循环
    for (auto &e : array)
    {
        e++;
    }

错误使用范围for

void test(int a[])
{
    for(auto&e : a)//报错!!必须是数组,这里a是指针
    {
        e++;
    }
}

关于NULL

在c语言中我们的指针喜欢定义为

int *pi=NULL;

但是在C++11后推荐使用nullptr

void f(int a)
{
    cout << "f(int a)" << endl;
}

void f(int*a)
{
    cout << "f(int*a)" << endl;
}


int main()
{
    f(NULL);
    f(0);
//打印的一样,因为NULL是宏,替换后为0,为整型类型。
    f(nullptr);//打印 "f(int*a)",nullptr整型指针类型。
}

使用在C++11以后指针初始化用nullptr

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云的小站

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值