C++深度解析(22)—初探C++標準庫

1.有趣的重載

  • 操作符<<的原生意義是按位左移,例: 1 << 2 ; 
  • 其意義是將整數1按位左移2位,即: 0000 0001  →  0000 0100     

2.編程實驗

  • 重載左移操作符     
  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; //使用endl替換'\n'
  31. cout << "Hello World" << endl;
  32. double a = 0.1;
  33. double b = 0.2;
  34. cout << a + b << endl;
  35. getchar();
  36. return 0;
  37. }
  • 運行結果:

3.C++標準庫

  • 很多時候程序設計不應該重複造輪子,而應該有效利用已有的實現

3.1 注意

  • C++標準庫並不是C++語言的一部分
  • C++標準庫是由類庫函數庫組成的集合
  • C++標準庫中定義的類和對象都位於std命名空間中
  • C++標準庫的頭文件都不帶.h後綴
  • C++標準庫涵蓋了C庫的功能

3.2 C++編譯環境的組成

  • C++標準庫預定義了多數常用的數據結構

  • 右邊c開頭爲C++標準庫爲C提供的子庫,即C++標準庫已經包含一個子庫用來兼容C語言代碼

3.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, "Hello World");
  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. getchar();
  17. return 0;
  18. }
  • C++中諸如stdio.h  math.h…….爲C++編譯廠商爲了推廣自己產品而推出的C兼容庫,不是標準C庫
  • 編譯C代碼就要改頭文件的話,麻煩。。。。。
  • 通過使用C兼容庫,現有的C代碼都可以被編譯啦,編譯器廠商就成功吸引用戶啦!!!

3.4 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 << "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. system("pause");
  16. return 0;
  17. }
  • 運行結果:

4.總結

  • C++標準庫是由類庫函數庫組成的集合
  • C++標準庫包含經典算法和數據結構的實現
  • C++標準庫涵蓋了C庫的功能
  • C++標準庫位於std命名空間中
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章