c++硬核学习 一些c++有c没有的数据类型

本文深入探讨了C++中的各种数据类型,包括char、wchar、bool、long、long long、auto等,解释了它们的用途、内存占用及如何正确使用。特别是对char和wchar的区别,以及如何在控制台输出中文进行了详细说明。

char 和 wchar

char:是单字节
wchar:是宽字节
宽字节是为了配合unicode编码格式而诞生的
需要输出宽字节的时候,需要使用wcout,用cout会出现一堆数字
需要输出中文的时候要加入wcout.imbue(locale(“chs”));这句话

// helloworld.cpp: 定义控制台应用程序的入口点。
//
#include <iostream>
using namespace std;
//命名空间
struct A{};
int main()
{
   
    /*********    一些c++有c没有的数据类型     **********/

    //单字节字符
    char a = 'A';
    wcout << a << "  " << sizeof(a) << endl;

    //宽字节字符 宽字输出用wcont
    wchar_t b = L'S';
    wcout << b << "  " << sizeof(a) << endl;

    //默认locale是en_us,如果要改成中文,要加入 wcout.imbue(locale("chs"))
    wchar_t d = L'中';
    wcout.imbue(locale("chs"));
    wcout << d << "  " << sizeof(a) << endl;

    return 0;
}


bool类型

c++的bool类型是首字符小写的true和false表示布尔值,这个对用习惯python的我特别的不友好
如果用数字表示布尔值,那么0为假,其他数字都为真。

// helloworld.cpp: 定义控制台应用程序的入口点。
//
#include <iostream>
using namespace std;
//命名空间
struct A{};
int main()
{
    /**bool类型**/
    bool b1 = true;
    bool b2 = false;
    bool b3 = 0; //0为假
    bool b4 = -1; // 非0为真
    cout << b1 << endl;
    cout << b2 << endl;
    cout << b3 << endl;
    cout << b4 << endl;

    return 0;
}


long 和 long long 类型

long 占四个字节,longlong占8个字节 实现了32位机器上可以扩展8字节的数据

// helloworld.cpp: 定义控制台应用程序的入口点。
//
#include <iostream>
using namespace std;
//命名空间
struct A{};
int main()
{

    /** long 和 longlong 类型 **/

    long a = 2147483647; // 2^31-1
    long b = 2147483648; // 2^31 溢出
    long c = 4294967296; // 2^32 溢出

    cout << a << " " << sizeof(a) << endl;
    cout << b << " " << sizeof(b) << endl;
    cout << c << " " << sizeof(c) << endl;

    long long d = 4294967296;
    cout << d << " " << sizeof(d) << endl;

    return 0;
}

输出

2147483647 4
-2147483648 4
0 4
4294967296 8

auto类型

auto类型 编译器自动分析表达式的类型
使用auto类型的时候一定要赋初值,不赋初值会报错。

// helloworld.cpp: 定义控制台应用程序的入口点。
//
#include <iostream>
using namespace std;
//命名空间
struct A{};
int main()
{
    /** auto 类型 **/
    auto a = 99;
    auto b = "Shanghai";
    auto c = L"b";
    auto d = 1.56f;
    auto e = &a;
    int f[2][3];
    auto g = f;
//    auto h; //需要初始值

    cout << a << " " << sizeof(a) << " " << typeid(a).name() << endl;
    cout << b << " " << sizeof(b) << " " << typeid(b).name() << endl;
    wcout << c << " " << sizeof(c) << " " << typeid(c).name() << endl;
    cout << d << " " << sizeof(d) << " " << typeid(d).name() << endl;
    cout << e << " " << sizeof(e) << " " << typeid(e).name() << endl;
    cout << g << " " << sizeof(g) << " " << typeid(g).name() << endl;

    return 0;
}


输出

99 4 int
Shanghai 4 char const *
b 4 wchar_t const *
1.56 4 float
003FF89C 4 int *
003FF86C 4 int (*)[3]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值