C++-nullptr-类型推导

1、nullptr(掌握)(NULL 就是0)

NULL 在源码当中就是0,因此可能会存在一些二义性的问题。

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


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

void func(char *b)
{
     
    cout << "b = " << b << endl;
}

int main()
{
     
    func(NULL); // a == 0
    return 0;
}

在C++11 中使用nullptr代替了NULL,作为空指针的表示方式。

#include <iostream>
#include <memory>
using namespace std;
void func(int a)
{
     
    cout << "a = " << a << endl;
}
void func(char *b)
{
     
    cout << "b = " << b << endl;
}
int main()
{
     
    func(nullptr); // b
    return 0;
}

2、类型推导(auto掌握)

使用auto关键字可以推导类型。

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

double test()
{
     
    return 1.1;
}

int main()
{
     

    auto i = 10;    // i的类型自动推导为整形(int)
    cout << i << endl;

    auto i2 = 19.4;
    cout << i2 << endl; // i2的类型自动推导为浮点型

    auto i3 = new auto(10); // i3的类型被推导为 int *
    cout << *i3 << endl;

    auto i4 = test();
    cout << i4 << endl;

    auto i5 = "hello";
    cout << i5 << endl;

    auto i6 = 'a';
    cout << i6 << endl;

    delete i3;
    i3 = nullptr;

    return 0;
}

decltype 可以推导表达式的类型,需要注意的是,decltype只会分析表达式的类型,不会具体计算表达式里的值。(熟悉)

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


int main()
{
     
    auto x = 1;
    auto y = 2;

    decltype(x+y+3*32+1.3) z = 888.32; //int + int *int + double = double;
    cout << z << endl;
    cout << sizeof(z) << endl;
    return 0;
}

相关推荐

  1. C++-nullptr-类型推导

    2024-01-09 22:48:02       38 阅读
  2. auto/范围for/nullptr(C++)

    2024-01-09 22:48:02       6 阅读
  3. C++从入门到精通——nullptr

    2024-01-09 22:48:02       22 阅读
  4. [C++11] nullptr完整解析

    2024-01-09 22:48:02       19 阅读
  5. C++不定参数模板、折叠表达式和类型推导

    2024-01-09 22:48:02       22 阅读
  6. 7.1 C++11指针空值—nullptr

    2024-01-09 22:48:02       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-09 22:48:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-09 22:48:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-09 22:48:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-09 22:48:02       20 阅读

热门阅读

  1. C++推箱子游戏开发

    2024-01-09 22:48:02       42 阅读
  2. Fixed win size sliding window

    2024-01-09 22:48:02       37 阅读
  3. 【Vue】项目使用px2rem

    2024-01-09 22:48:02       40 阅读
  4. React使用Valtio的hook实现响应式状态管理

    2024-01-09 22:48:02       34 阅读
  5. 发音纠正(每日职场英语)

    2024-01-09 22:48:02       38 阅读
  6. AI智能电销器人需要注意哪些问题呢

    2024-01-09 22:48:02       38 阅读