1. scope
local scope, function scope, class scope, file scope, prototype scope.
2. const
const: read only, the const keyword specifies that the object or variable is not modifiable.
定义时必须初始化;const对象默认为文件的局部变量,必须显式的使用extern才能使其在其他文件中访问,(非const变量默认为extern);A pointer to a variable declared as const can be assigned only to a pointer that is also declared as const.如下:const修饰指针变量,地址不可以变,值可以变。
char*mybuf = 0, *yourbuf; char *const aptr = mybuf; *aptr = 'a'; // OK aptr = yourbuf; // C3892
const修饰指针变量中的数据,数据不可以变,用于函数传参,保证参数不被修改。地址可以变。
const char *mybuf = "test"; char *yourbuf = "test2"; printf_s("%s\n", mybuf);
3. reference &
引用是对象的另一名字。
4.通过溢出来产生随机数:
#include <iostream> using namespace std; unsigned srand(){ static unsigned int seed = 5255; seed = (8989859*seed)+3341324; return seed % 32767; } int main() { int count = 10; for(int i=0; i<count; i++) std::cout << srand()<<endl; return 0; }
4个字节整数可以存10位数,找个4位数乘以7位数就会产生溢出,溢出的数无法预测,可以作为随机数。
5.声明可以出现很多次,但是定义只能出现一次。
下面是使用函数指针实现选择排序,增序,降序、以及偶数在前的增叙。
#include <iostream> #include <algorithm> using namespace std; typedef bool(*pComparsion)(int,int); void selectionSort(int *a, int n, pComparsion pCom){ for(int i = 0; i < n; i++){ int best=i; for(int j = i+1; j < n; j++){ if(pCom(a[j],a[best])) best = j; } swap(a[best],a[i]); } } bool ascending(int x, int y){ return x < y; } bool descending(int x, int y){ return x > y; } bool evenFirst(int x, int y){ if(x%2 == 0 && y%2 != 0) return true; if(x%2 != 0 && y%2 == 0) return false; ascending(x,y); } void printArr(int *a, int n){ for(int i = 0; i < n; i++){ cout << a[i] <<" "; } } int main(){ int arr[9] = {3, 7, 9, 5, 6, 1, 8, 2, 4}; selectionSort(arr,9,ascending); printArr(arr,9); cout << endl; selectionSort(arr,9,descending); printArr(arr,9); cout << endl; selectionSort(arr,9,evenFirst); printArr(arr,9); }
1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 2 4 6 8 1 3 5 7 9