運算子 & , * , []
int i = 5487 ;
int* pi = &i;
cout << &i << endl; //0x28fef8
cout << *pi << endl; //5487
cout << *&i << endl; //5487
cout << *&*pi << endl; //5487
- array[index] :同 *(array+index)
但是! 因為C++可以重載運算子,所以也可以修改這個運算子,讓他的功能跟這裡寫得不一樣,這裡寫的只是預設。
int array[3] = { 10, 20, 30 };
cout << array[1] << endl ; //20
cout << *(array+2) <<endl; //30
cout << array[3] << endl ; //5487 緩衝區溢位(為什麼不是pi的內容,我猜是編譯器自動優化)
int a0 = 1000;
int a1 = 2000;
char c[4] = {3,2,0,0};
int a[3] = {300,400,500};
cout<< a[3] <<endl; //515 = 3*1 + 2*256
cout<< a[4] <<endl; //2000
cout<< a[5] <<endl; //1000
int a0 = 1000;
int a1 = 2000;
char c[2] = {3,2};
int a[3] = {300,400,500};
cout<< a[3] <<endl; //515+???
cout<< a[4] <<endl; //2000
cout<< a[5] <<endl; //1000
class A{
char a;
int b;
bool c;
};
class B{
char a;
bool b;
int c;
};
//main()
cout<< sizeof(A) <<endl; //12
cout<< sizeof(B) <<endl; //8
指標,參考
宣告type* ptr;
配置一塊4bytes的記憶體(因為是32bit程式,address大小32bit)
宣告type& ref = var;
會不會配置記憶體給他??我不知道
int i = 5487 ;
int* ptri = &i;
int& refi = i;
cout<< i <<endl; //5487
cout<< ptri <<endl; //0x28fef8
cout<< refi <<endl; //5487
看這三個變數的記憶體位置,i 和 refi 是一樣的
cout<< &i <<endl; //0x28fef8
cout<< &ptri <<endl; //0x28fef4
cout<< &refi <<endl; //0x28fef8
- call by value
- call by pointer
- call by reference
void byVal(int val){
cout<< &val;
++val;
}
void byPtr(int* ptr){
cout<< &ptr;
++(*ptr);
}
void byRef(int& ref){
cout<< &ref;
++ref;
}
//main()
int i = 5487 ;
cout << &i <<endl;//0x28fefc
byVal(i); //0x28fee0
cout<< i <<endl; //5487
byPtr(&i); //0x28fee0
cout<< i <<endl; //5488
byRef(i); //0x28fefc
cout<< i <<endl; //5489
type function();
- return value
- return pointer
- return reference
只要argument的部分懂了,這個就懂了
只是這裡主要用在class裡面。
class Test{
public:
int a;
Test(int a):a(a){}
int getAVal(){ return a;}
int* getAPtr(){ return &a;}
int& getARef(){ return a;}
Test* retThis(){ return this;}
};
//main()
Test obj(0);
cout<< obj.a <<endl; //0
//obj.getAVal()++; //error:回傳值無法改變
( *( obj.getAPtr() ) )++;
cout<< obj.a <<endl; //1
obj.getARef()++;
cout<< obj.a <<endl; //2
obj.retThis()->getARef()++;
cout<< obj.a <<endl; //3
new delete
int size;
int* dynArray;
cin>>size;
dynArray = new int[size];
//do something
delete[] dynArray;//用完後要delete
int size;
cin>>size;
int arr[size];//應該會有編譯error,但不知道為什麼我測試沒有,求解