1.有趣的重載
- 操作符<<的原生意義是按位左移,例: 1 << 2 ;
- 其意義是將整數1按位左移2位,即: 0000 0001 → 0000 0100
2.編程實驗
- 重載左移操作符
- #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; //使用endl替換'\n'
- cout << "Hello World" << endl;
- double a = 0.1;
- double b = 0.2;
- cout << a + b << endl;
-
- getchar();
-
- return 0;
- }
- 運行結果:
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庫兼容
- #include<cstdio>
- #include<cstring>
- #include<cstdlib>
- #include<cmath>
-
- using namespace std;
-
- int main()
- {
- printf("Hello World!\n");
- char *p = (char *)malloc(16);
- strcpy(p, "Hello World");
- double a = 3;
- double b = 4;
- double c = sqrt(a*a + b * b);
- printf("c = %f\n", c);
-
- free(p);
-
- getchar();
-
- return 0;
-
- }
- C++中諸如stdio.h math.h…….爲C++編譯廠商爲了推廣自己產品而推出的C兼容庫,不是標準C庫
- 編譯C代碼就要改頭文件的話,麻煩。。。。。
- 通過使用C兼容庫,現有的C代碼都可以被編譯啦,編譯器廠商就成功吸引用戶啦!!!
3.4 C++中的輸入輸出
- #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;
-
- system("pause");
-
- return 0;
- }
- 運行結果:
4.總結
- C++標準庫是由類庫和函數庫組成的集合
- C++標準庫包含經典算法和數據結構的實現
- C++標準庫涵蓋了C庫的功能
- C++標準庫位於
std
命名空間中