2017年7月17日 星期一

ch 7 function & const 位置

con7.x

參數傳遞,要了解const,reference,pointer的關係
pass by value、pass by address、pass by reference

  • 前兩種(pass by value、pass by addres)都是把值複製過去給參數, 差別在一個複製指標一個複製值,如果copy std::string 會異常的大
  • pass by reference 是在初始化時就把物件綁定


注意:
string& str= const string str //error
const string str=string& str //ok 但不能改值

const 位置
1. const修飾普通變數和指標

(1)  指針本身是常量不可變(不可指向別處)
int* const pContent;

(2)  指標所指向的內容是常量不可變
const int* pContent;


(3)  兩者都不可變
const int* const pContent;

2. const修飾函數參數
void function(const char* Var); //參數指標所指內容為常量不可變

void function(char* const Var); //參數指標本身為常量不可變(也無意義, 因為char* Var也是形參)

3. const 修飾函數返回值
const int * fun2()
調用時 const int *pValue = fun2();

int* const fun3()
調用時 int * const pValue = fun3();


4. const修飾類物件/物件指標/物件引用

const 物件只能調用有const function, 不能調用non-const function

class AAA
{
   void func1();


void func2() const;
}
const AAA aObj;
aObj.func1(); //error
aObj.func2(); 正確


const function can't call non-const function


void AAA::func2() const
{
func1(); // error
}


5. const常量與define巨集定義的區別
(1) 編譯器處理方式不同
define宏是在預處理階段展開。
const常量是編譯運行階段使用。
(2) 類型和安全檢查不同
define宏沒有類型,不做任何類型檢查,僅僅是展開。
const常量有具體的類型,在編譯階段會執行類型檢查。
(3) 存儲方式不同
define宏僅僅是展開,有多少地方使用,就展開多少次,不會分配記憶體。
const常量會在記憶體中分配(可以是堆中也可以是棧中)。



參考: 鏈結


7.8 Overloaded Functions



定義:同一區域,傭有兩個以上相同名稱的function,但參數不同(回傳不算)
p.s. overload 少用,同一function name 但是參數不同,意義不容易理解


function matching result:
1.完全符合
2.no match function, error
3.ambiguous
ex:
void fun(int a)
void fun(int a,int b=1)


7.9 Pointers to functions


例如:pthread_create 有用到

int pow(int value)
{
    printf("pow pow pow \n");
    return value*value;
}
void custom_for_each(  int (*functionPointer)( int ) )
{
    printf("custom_for_each \n");
    printf("....%d\n",(*functionPointer)( 2 ));
}

int main(int argc, char *argv[])
{
    custom_for_each(&pow);
    

}



typedefine 定義
typedef int (*functionPointer)( int );

void custom_for_each( functionPointer fun )
{....}

沒有留言:

張貼留言