1. 程式人生 > >C++技術——預設引數

C++技術——預設引數

1 預設引數特點:

(1)宣告和定義的形式不一樣:預設引數在函式宣告的時候寫, 定義的時候不需要寫。

(2)如果引用使用預設引數,則預設引數的值必須全域性變數的值,因為預設引數的值需要在函式宣告時就指定,只能通過全域性變數的值來引用,不可通過函式傳值來賦值,那樣的話表示是呼叫的時候才賦值,這不符合預設引數的定義。

#include <iostream>
using namespace std;

int ar=10;

void show(int &a, int &b=ar)
{
	cout<<"(a,b)"<<a<<","<<b<<endl;
}

(3)當函式過載與預設引數同時出現時,像下面的例子就存在歧義,們把兩者合為一體。

#include <iostream>  
using namespace std;  
  
//預設函式
void DefaultArguTest(int arg1 = 1, int arg2 = 2, int arg3 = 3)
{  
    cout<<arg1<<" "<<arg2<<" "<<arg3<<endl;  
}

//過載  
void DefaultArguTest()
{
    cout<<"DefaultArguTest"<<endl;
} 
  
int main(void)  
{  
    //不給引數  
    DefaultArguTest();  
  
    system("pause");  
    return 0;  
}  
  

(4)複寫函式時不要更改預設引數。

#include <iostream>  
#include <string>  
using namespace std;  
  
class Base  
{  
public:  
    virtual void Print(int i = 1, int j = 2)  
    {  
        cout<<"In base: "<<i<<" "<<j<<endl;  
    }  
};  
  
class Child : public Base  
{  
public:  
    //手動的將預設引數修改了。
    void Print(int i = 3, int j  = 4 )  
    {  
        cout<<"In Child: "<<i<<" "<<j<<endl;  
    }  
};  

int main(void)  
{  
    //靜態繫結  
    cout<<"Static bind:"<<endl;  
    Child* child = new Child();  
    child->Print();  
  
    //動態繫結  
    cout<<"Dynamic bind:"<<endl;  
    Base* base = new Child();  
    base->Print();  
      
  
    system("pause");  
    return 0;  
}  

結果:
Static bind:
In Child: 3 4
Dynamic bind:
In Child: 1 2 //理論上錯的,應該是:In Child: 3 4 
因為為了效率,函式的預設引數是使用靜態繫結的,換句話說,
不管你有沒有多型,我只關心你用什麼指標來調,基類指標就調
用基類的預設引數,子類指標就給出子類的預設引數。而不像我們
多型那樣,會發生動態繫結,可以用基類指標呼叫子類函式。而我們
在一個動態繫結的函式中使用了靜態繫結的引數,結果肯定是不對的!