[C++] 十二nullptr、类型推导、格式化输出、字符串与数字之间的转换


nullptr

在C++11中,NULL使用nullptr来代替

#include <iostream>

using namespace std;

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

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

int main()
{
    // NULL就是0
    func(NULL); // 1
    func(nullptr); // 2

    return 0;
}

类型推导auto、decltype

C++11中引入,使用auto关键字可以进行类型推导
!!auto不能在参数类型和数组中使用

#include <iostream>

using namespace std;

class Test
{
public:
    void func()
    {
        cout << "hello" << endl;
    }
};

int main()
{
    auto i = 1;
    auto d = 3.14;
    auto a = i+d;
    cout << a << endl; // 4.14

    // t的类型被推导为Test*
    auto t = new Test;
    cout << t << endl;
    t->func();

    return 0;
}

auto只能对变量进行类型推导,decltype可以对表达式进行类型推导

#include <iostream>

using namespace std;

class Test
{
public:
    void func()
    {
        cout << "hello" << endl;
    }
};

int main()
{
    int i = 1;
    double d = 3.14;
    // 计算i*d这个表达式的数据类型
    // 因为z是浮点型,所以此处的z为double类型
    decltype(i*d) z = 2.22;
    cout << z << endl;

    return 0;
}

格式化输出

#include <iostream>
#include <iomanip> // 输出域

using namespace std;

int main()
{
    int i = 10;
    // 开启进制显示功能(十进制无效)
    cout << showbase;
    // 切换为8进制输出
    cout << oct;
    cout << i << endl; // 012
    // 切换为16进制输出
    cout << hex;
    cout << i << endl; // 0xa
    // 切换回十进制
    cout << dec;
    cout << i << endl; // 10
    // 取消进制显示
    cout << noshowbase;
    // 设置输出域的宽度
    // 如果设置输出域宽度小于数据宽度,还会显示数据宽度
    cout << setw(7) << "1=1x1" << endl;
    cout << setw(1) << "2=1x2" << setw(7) << "4=2x2" << endl;
    cout << setw(7) << "15=3x5" << setw(7) << "81=9x9" << endl;
    return 0;
}

字符串与数字转换

借助字符串流来完成字符串与数字之间的转换,需要引入头文件:

//我这么写总不会再因为尖括号隐藏吧
#include <sstream>
#include <iostream>
#include <sstream> // 字符串流

using namespace std;

int main()
{
    // int → string
    int i = 123;
    stringstream ss;
    ss << i;
    string s = ss.str();
    cout << s.append("abc") << endl;

    // string → int
    s = "666";
    stringstream ss2(s);
    ss2 >> i;
    cout << ++i << endl;

    return 0;
}

C++内容到这基本就结束了,我也发现自己写的还是太基础、还有好多需要学习的地方,如果哪里有什么问题欢迎指出,一起学习,后续大家一起加油吧

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值