一、標準庫「引子」:
1、操作符"<<"的原生意義是按位左移,例如:
1<<2它的意義是將整數1按位左移2位,即:
0000 0001 演變成 0000 0100重載左移操作符,將變量或者常量左移到一個對象中
代碼示例:
#include <stdio.h>
const char endl = '\n';
class Console
{
public:
Console& operator <<(int i)
{
printf("%d\n",i);
return *this;
}
Console& operator << (char c)
{
printf("%c\n",c);
return *this;
}
Console& operator <<(const char* s)
{
printf("%s\n",s);
return *this;
}
Console& operator << (double d)
{
printf("%f\n",d);
return *this;
}
};
Console cout;
int main()
{
cout<<1 << endl;
cout<<"TXP"<<endl;
double a = 0.1;
double b = 0.2;
cout << a + b <<endl;
return 0;
}運行結果:
root@txp-virtual-machine:/home/txp# ./a.out
1
TXP
0.300000從上面我們可以看到,不直接使用printf函數去列印這個值,這個以前在書上,都是直接講解把數值說送到輸出流中去,但是你一開始學習cout函數(或者說你還沒有接觸到對象的時候,根本不明白這什麼意思);如果進行了左移的重載之後,那麼程序將產生神奇的變化,所以在 main() 中不用 printf() 和格式化字符串 '\n' 了,因為編譯器會通過重載的機制會為我們選擇究竟使用哪一個重載機制。
二、c++標準庫:
1、標準庫的特性:
2、C++編譯環境的組成:
3、C++標準庫預定義了很多常用的數據結構:
-<bitset> -<set> -<cstdio>
-<deque> -<stack> -<cstring>
-<list> -<vector> -<cstdlib>
-<queue> -<map> -<cmath>代碼示例:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;//所謂命名空間,是一種將程序庫名稱封裝起來的方法,它就像在各個程序庫中立起一道道圍牆
int main()
{
printf("Hello world!\n");
char* p = (char*)malloc(16);
strcpy(p, "TXP");
double a = 3;
double b = 4;
double c = sqrt(a * a + b * b);
printf("c = %f\n", c);
free(p);
return 0;
}輸出結果:
root@txp-virtual-machine:/home/txp# ./a.out
Hello world!
c = 5.000000註:關於命名空間的介紹,這裡沒有詳細的去介紹,後面會重新做一個詳細介紹。
4、cout和cin兩個函數形象比喻:
代碼示例:
#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;
return 0;
}結果輸出:
root@txp-virtual-machine:/home/txp# ./a.out
Hello world!
Input a: 3
Input b: 5
c = 5.83095當然這裡關於cout和cin兩個函數裡面的細節也沒有寫明;不過如果接觸過C++的朋友,現在看起來,現在這種寫法,更加c++正統一點,之前的寫法都是c寫法,除了類的寫法之外。
三、總結:
C++標準庫是由類庫和函數庫組成的集合
C++標準庫包含經典算法和數據結構的實現
C++標準庫涵蓋了C庫的功能
C++標準庫位於std命名空間中