C++之標(biāo)準(zhǔn)庫的學(xué)習(xí)總結(jié)
一、標(biāo)準(zhǔn)庫“引子”:
1、操作符"<<"的原生意義是按位左移,例如:
1<<2
它的意義是將整數(shù)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;
}
運(yùn)行結(jié)果:
root@txp-virtual-machine:/home/txp# ./a.out
1
TXP
0.300000
從上面我們可以看到,不直接使用printf函數(shù)去打印這個值,這個以前在書上,都是直接講解把數(shù)值說送到輸出流中去,但是你一開始學(xué)習(xí)cout函數(shù)(或者說你還沒有接觸到對象的時候,根本不明白這什么意思);如果進(jìn)行了左移的重載之后,那么程序?qū)a(chǎn)生神奇的變化,所以在 main() 中不用 printf() 和格式化字符串 '\n' 了,因?yàn)榫幾g器會通過重載的機(jī)制會為我們選擇究竟使用哪一個重載機(jī)制。
二、c++標(biāo)準(zhǔn)庫:
1、標(biāo)準(zhǔn)庫的特性:
C++標(biāo)準(zhǔn)庫并不是C++語言的一部分
C++標(biāo)準(zhǔn)庫是由類庫和函數(shù)庫組成的集合
C++標(biāo)準(zhǔn)庫中定義的類和對象都位于std命名空間中
C++標(biāo)準(zhǔn)庫的頭文件都不帶.h后綴,當(dāng)然也兼容c語言里面的.h寫法
C++標(biāo)準(zhǔn)庫涵蓋了C庫的功能
2、C++編譯環(huán)境的組成:
3、C++標(biāo)準(zhǔn)庫預(yù)定義了很多常用的數(shù)據(jù)結(jié)構(gòu):
-<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;
}
輸出結(jié)果:
root@txp-virtual-machine:/home/txp# ./a.out
Hello world!
c = 5.000000
注:關(guān)于命名空間的介紹,這里沒有詳細(xì)的去介紹,后面會重新做一個詳細(xì)介紹。
4、cout和cin兩個函數(shù)形象比喻:
代碼示例:
#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;
}
結(jié)果輸出:
root@txp-virtual-machine:/home/txp# ./a.out
Hello world!
Input a: 3
Input b: 5
c = 5.83095
當(dāng)然這里關(guān)于cout和cin兩個函數(shù)里面的細(xì)節(jié)也沒有寫明;不過如果接觸過C++的朋友,現(xiàn)在看起來,現(xiàn)在這種寫法,更加c++正統(tǒng)一點(diǎn),之前的寫法都是c寫法,除了類的寫法之外。
三、總結(jié):
C++標(biāo)準(zhǔn)庫是由類庫和函數(shù)庫組成的集合
C++標(biāo)準(zhǔn)庫包含經(jīng)典算法和數(shù)據(jù)結(jié)構(gòu)的實(shí)現(xiàn)
C++標(biāo)準(zhǔn)庫涵蓋了C庫的功能
C++標(biāo)準(zhǔn)庫位于std命名空間中
免責(zé)聲明:本文內(nèi)容由21ic獲得授權(quán)后發(fā)布,版權(quán)歸原作者所有,本平臺僅提供信息存儲服務(wù)。文章僅代表作者個人觀點(diǎn),不代表本平臺立場,如有問題,請聯(lián)系我們,謝謝!