1.有趣的重载

操作符<<的原生意义是按位左移
重载左移操作符,将变量或者常量左移到一个对象中

  1. //重载<<的演示
  2. #include<stdio.h>
  3. const char endl = '\n';
  4. class Console
  5. {
  6. public:
  7. int operator <<(int i)
  8. {
  9. printf("%d", i);
  10. return i;
  11. }
  12. Console& operator <<(char c)
  13. {
  14. printf("%c", c);
  15. return *this;
  16. }
  17. };
  18. Console cout;
  19. int main()
  20. {
  21. cout << 1 << endl;
  22. //cout << "\n";
  23. return 0;
  24. }

这种很好的方法,前人已经实现在c++的标准库了

2.c++标准库

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

Slide6.PNG
Slide7.PNG

3.c++标准库中的c兼容

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

显示器——————-》cout c++标准库中的显示器对象
键盘———————-》cin c++标准库中的键盘对象

实验:完全由c++标准库实现

  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 << "inputa a: ";
  10. cin >> a;
  11. cout << "inputa b: ";
  12. cin >> b;
  13. double c = sqrt( a * a + b * b);
  14. cout << "c = " << c << endl;
  15. return 0;
  16. }

from now on!
用c++标准库!!!!!!


小结:

1.c++标准库由类库和函数库组成的集合
2.c++标准库包含经典算法和数据结构的实现
3.c++标准库涵盖了c库的功能
4.c++标准库位于std命名空间