1、定義枚舉類型
//定義枚舉類型,其中對應的分別是 0 1 2 3 4。。。
enum spectrum {red, orange, yellow, green, blue};
spectrum band;
- 枚舉類型的賦值只能是定義的成員之一
- 枚舉類型中沒有算數運算
band =red; //合法 成員之一
band=20; //不合法,非枚舉成員
++band; //不合法
band = blue + 1; //不合法
band = 2: //不合法
band = (color)2; //合法
- 自定義枚舉類型初始值,未指定默認從0開始遞增
enum bit { one =1; two =2, four =4, eight =8};
2、注意 new和 delete 的配對使用,防止內存泄漏,防止兩次釋放同一個區域的錯誤。
3、靜態聯編:靜態數組 ,在編譯時候確定數組的大小;
動態聯編:動態數組,運行時候確定大小
int * psome =new int[10];
delete [] psome; //釋放數組
4、無法使用sizeof 獲得 動態數組的大小
int a = 10;
int * b = new int;
int c[10] = { 1, 2 };
int *d = new int[15];
cout << "sizeof a :" << sizeof(a) << endl;
cout << "sizeof b :" << sizeof(*b) << endl;
cout << "sizeof c :" << sizeof(c) << endl;
cout << "sizeof d :" << sizeof(*d) << endl;
5、自動存儲,靜態存儲,動態存儲
-自動存儲 ,也就是局部變量,生命週期在一個代碼塊內 {},棧上建立
如下的代碼塊中,每次循環重新生成一個變量,其聲明週期只在 花括號內
while (1)
{
int a =4;
}
-靜態存儲 static 堆上建立
-動態存儲 使用new ,生命週期不受控制
6、
數組的替代 模板類 vector array
vector
- 初始長度可以指定爲0,長度可以變化
- 但是效率低
- 存儲在棧中
#include <vector> //頭文件
...
vector<int> vi;
int n=6;
vector<double> vd(n);//可以使用變量制定生成的數組長度
array
- array的長度固定,不能使用變量定義長度
- 存儲在堆中
- array之間可以直接賦值運算
#include <array>
...
array<int,5> ai;
array<double, 4> ad ={1.2, 1.4, 6.7, 1.8};
array<double, 4> ac=ad;
7、逗號運算符結合兩個表達式, 使其只佔用一個表達式的位置
for (int i=0; i<5; i++)
int j=0, double k=1.0; //可以結合兩個變量定義
cata =17, 240;
cata2 =(17,240);
逗號運算符,使得前面的有優先級,而括號使得後面的那個優先級更高
int cata,cata2;
cata = 17, 20;
cata2 = (17, 20);
cout << "cata :" << cata << " cata2: " << cata2 << endl;
8、string 類的對象可以直接比較字符串,但是C語言風格的需要使用strcmp來比較兩個字符串+
9、基於範圍的for 循環 ,其中括號不能省略
double prices[5] = { 3.44, 1.99, 3.5, 4.9, 2.9};
for (double x : price)
{
cout << "xx : " <<x <<endl;
}
10、指針數組存儲字符串; 二維數組存儲字符串
const char * cities[2] =
{
"Gribble City",
"New Gribble"
};
//二維數組的方式存儲, 限定單個長度不超過24
const char cities[2][24] =
{
"Gribble City",
"New Gribble"
};
11、switch 表達式中必須使用 整形表達式,int char 枚舉類型等