【C++】 32_初探 C++ 标准库

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【C++】 32_初探 C++ 标准库脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

有趣的重载

操作符 << 的原生意义是按位左移: 1 << 2;
其意义是将整数 1 按位左移 2 位,即: 0000 0001 ==> 0000 0100

重载左移操作符,将变量或常量左移到一个对象中!

编程实验: 重载左移操作符

#include <stdio.h>

const char endl = 'n';

class Console
{
public:
    Console& operator << (int i)
    {
        printf("%d", i);
        
        return *this;
    }
    Console& operator << (char c)
    {
        printf("%c", c);
        
        return *this;
    }
    Console& operator << (const char* s)
    {
        printf("%s", s);
        
        return *this;
    }
    Console& operator << (double d)
    {
        printf("%f", d);
        
        return *this;
    }
};

Console cout;

int main()
{
    cout << 1 << endl;
    cout << "D.T.Software" << endl;
    
    double a = 0.1;
    double b = 0.2;
    
    cout << a + b << endl;

    return 0;
}
输出:
1
D.T.Software
0.300000

C++ 标准库

重复发明轮子并不是一件有创造性的事,站在巨人的肩膀上解决问题会更加高效!

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

  • C++ 编译环境的组成

【C++】 32_初探 C++ 标准库

  • C++ 扩展语法模块、编译器扩展库:编译器厂商决定,不同编译器不同
  • C 语言兼容库:非 C 库,与 C 库头文件名相同,编译器厂商为了推广 C++ 编译器而增加,可以无缝编译 C 文件

    • <stdio.h> <;math.h> <string.h>
  • C++ 标准库 C 兼容模块:与原 C 库函数功能相同

    • <cstdio> <cmath> <cstring>
  • C++ 标准库预定义了多数常用的数据结构
<bITset> <set> <cstdio>
<deque> <stack> <cstring>
<list> <vector> <cstdlib>
<queue> <map> <cmath>

编程实验: C++ 标准库中的 C 库兼容

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

int main()
{
    printf("hello word!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 = %fn", c);
    
    free(p);

    return 0;
}
输出:
hello word!
c = 5.000000

【C++】 32_初探 C++ 标准库

编程实验: C++ 中的输入输出

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    cout << "hello word!" << 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;
}
输出:
hello word!
Input a: 3
Input b: 4
c = 5

小结

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

以上内容参考狄泰软件学院系列课程,请大家保护原创

脚本宝典总结

以上是脚本宝典为你收集整理的【C++】 32_初探 C++ 标准库全部内容,希望文章能够帮你解决【C++】 32_初探 C++ 标准库所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。