2010-01-08 47 views
0

我在這裏有一個程序: 我有一個疑問在函數display()傳遞參數。如何選擇傳遞給函數的默認參數

void display(int = 20,int = 30,int = 50); 

int main() 
{ 
    display(5,12); 
    return 0; 
} 

void display(int i,int j,int k) 
{ 
    cout<<i<<endl; 
    cout<<j<<endl; 
    cout<<k<<endl; 
} 

如果此功能顯示是通過傳遞2個參數來叫, 如何才能確保這些參數分別作爲第一和第三, 而第二個參數是默認處理。

回答

3

你不能。最後的默認參數是ALWAYS。

,你能做的最好是類似以下的模式:

// Choose a number that is NEVER valid as input to represent default: 
#define DEFAULT_VAL 0x7fffffff 

void display (int i, int j, int k) 
{ 
    if (i == DEFAULT_VAL) i = 20; 
    if (j == DEFAULT_VAL) i = 30; 
    if (k == DEFAULT_VAL) i = 50; 

    cout<<i<<endl; 
    cout<<j<<endl; 
    cout<<k<<endl; 
} 

堅持不住了,我才意識到,這是C++。在這種情況下,你可以使用函數重載來模擬你想要的:

void display (int i, int j, int k) 
{   
    cout<<i<<endl; 
    cout<<j<<endl; 
    cout<<k<<endl; 
} 

void display (int i, int k) 
{   
    cout<<i<<endl; 
    cout<<30<<endl; 
    cout<<k<<endl; 
} 

那麼,兩者都有優點和缺點。取決於你真正想做的事情。

+0

請不要使用重載 - 是的它的工作原理,但它非常混亂。 – 2010-01-08 16:24:49

2

不幸的是,你不能。只有尾隨參數可以使用C++中的默認參數。

如果這是一個問題,你既可以:

  • 重新排序參數
  • 編寫函數的另一重載。
2

正如其他人所說的,您不能在非默認參數之間混合默認參數。獲得類似行爲的一種方法是使用結構來傳入參數,並只設置所需的值。 A la:

#include <cstdlib> 
#include <iostream> 
using namespace std; 

struct FnParams 
{ 
    int i, j, k; 
    FnParams() : i(20), j(30), k(40) {}; 
}; 

void DoTheThing(FnParams params = FnParams()) 
{ 
    cout << params.i << endl; 
    cout << params.j << endl; 
    cout << params.k << endl; 
} 

int main() 
{ 
    DoTheThing(); 

    FnParams p; 
    p.j = 42; 
    DoTheThing(p); 

    return 0; 
} 

沒有太多的功能受益於這種結構。但是隨着時間的推移,這些增長趨勢會不斷增長,新的參數被添加,舊的被刪除等等。上面的方法帶來了額外的好處,使得更容易改變傳遞給函數的參數,而不需要觸及1000的在每次進行小改動時都會調用函數的代碼。