9 c++标准库

image.png

(1)左移、右移操作符重载
a. 操作符<<的原生意义是按位左移,如 1<< 2
b. 意义000 0001-> 000 0100
c. 代码1重载左移操作符,将变量或常量左移到一个对象中:

  1. #include <stdio.h>
  2. const char endl = '\n';
  3. class Console
  4. {
  5. public:
  6. Console& operator << (int i)
  7. {
  8. printf("%d", i);
  9. return *this;
  10. }
  11. Console& operator << (char c)
  12. {
  13. printf("%c", c);
  14. return *this;
  15. }
  16. Console& operator << (const char* s)
  17. {
  18. printf("%s", s);
  19. return *this;
  20. }
  21. Console& operator << (double d)
  22. {
  23. printf("%f", d);
  24. return *this;
  25. }
  26. };
  27. Console cout;
  28. int main()
  29. {
  30. cout << 1 << endl;
  31. cout << "Software" << endl;
  32. double a = 0.1;
  33. double b = 0.2;
  34. cout << a + b << endl;
  35. return 0;
  36. }

运行结果:
image.png

(2)c++标准库概述
a. c++标准库不是c++语言的一部分
b. c++标准库是由类库和函数库组成的集合
c. 库中定义的类和对象都位于std命名空间中
d. 库的头文件都不带.h
e. c++标准库涵盖了c库的功能
(3)C++标准库预定义了多数常用的数据结构
image.png
代码2 初探标准库#include

  1. #include <cstring>
  2. #include <cstdlib>
  3. #include <cmath>
  4. using namespace std;
  5. int main()
  6. {
  7. printf("Hello world!\n");
  8. char* p = (char*)malloc(16);
  9. strcpy(p, "D.T.Software");
  10. double a = 3;
  11. double b = 4;
  12. double c = sqrt(a * a + b * b);
  13. printf("c = %f\n", c);
  14. free(p);
  15. return 0;
  16. }

运行结果:
image.png

(4)标准库使用
代码3输入输出流使用:

  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. int main()
  5. {
  6. cout << "Hello world!" << endl;
  7. double a = 0;
  8. double b = 0;
  9. cout << "Input a: ";
  10. cin >> a;
  11. cout << "Input b: ";
  12. cin >> b;
  13. double c = sqrt(a * a + b * b);
  14. cout << "c = " << c << endl;
  15. return 0;
  16. }


运行结果:
image.png