第32课初探C++标准库

本文内容来自于对狄泰学院 唐佐林老师 C++深度解析 课程的学习总结

前面的课程中我们学习了操作符的重载,那么 << 和 >> 操作符可以重载吗?我们来写一个类,重载 << 操作符来实现将整数和字符输出到控制台的功能。

实验代码
#include <stdio.h>

char endl = '\n';

class Console
{
private:
    /* data */
public:
    Console& operator << (int i)
    {
        printf("%d", i);
        return *this;
    }

    Console& operator << (char c)
    {
        printf("%c", c);
        return *this;
    }
};


Console cout;

int main()
{
    cout << 1 << endl;

    return 0;
}

运行结果
在这里插入图片描述

实验结果:程序实现了整数 1 和 转义字符 ‘\n’ 输出到控制台的功能

实际上,在 C++ 标准库中已经实现了上面 Console 类的功能。




C++ 标准库

C++ 标准库并 不是 C++ 语言的一部分
C++ 标准库是由 类库 函数库 组成的集合
C++ 标准库中定义的类和对象都位于 std 命名空间中
C++ 标准库的头文件都 不带 .h 后缀
C++ 标准库 涵盖了C库的功能

C++ 编译环境 的组成
在这里插入图片描述
C++ 标准库中定义了多数的数据结构
在这里插入图片描述

C语言兼容库

为了兼容C语言,C++ 编译器中包含了C语言兼容库,C中的stdio.h,在C语言兼容库中为cstdio
我们来写一个程序来测试C语言兼容库对C代码的兼容

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>

using namespace std;

int main()
{
    printf("hello world!\n");

    char *p = (char *)malloc(16);

    strcpy(p, "D.T.Software");

    double a = 3;
    double b = 4;
    double c = sqrt(a*a + b*b);

    printf("c = %f\n", c);

    printf("p = %s\n", p);

    free(p);

    return 0;
}

运行结果
在这里插入图片描述

实验结果,C++ 编译器的C兼容库可以对 C 语言进行很好的兼容




C++ 标准库

在这里插入图片描述

下面, 我们来用C++标准库 iostream 中的输入输出功能
实验代码

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    cout << "hello world!" << endl;

    double a = 0;
    double b = 0;

    cout << "input a:";
    cin >> a;

    cout << "input b:";
    cin >> b;

    double c = sqrt(a*a + b*b);

    cout << "c" << c << endl;

    return 0;

}



小结

C++ 标准库是由 类库函数库 组成的集合
C++ 标准库包含经典 算法 数据结构 的实现
C++ 标准库 涵盖了 C 库的功能
C++ 标准库位于 std 命名空间中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lzg2021

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

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

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

打赏作者

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

抵扣说明:

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

余额充值