2010-12-10 15 views

回答

2

http://cpptruths.blogspot.com/2005/07/changing-c-function-default-arguments.html

在C++中,全局範圍函數默認參數可以容易地改變。

通常我們使用常量表達式作爲默認參數。 C++支持靜態變量以及默認參數的常量表達式。我們還可以在具有不同默認值的新範圍中重新聲明函數簽名。

默認參數是作爲全局靜態變量實現的。因此,如果我們爲靜態varibale賦予不同的值,也可以達到同樣的效果。以下代碼顯示了此有趣的功能。


#include 
#include 
#include 

static int para=200; 

void g(int x=para); // default argument is a static variable. 
void f(int x=7); // default argument implemented in terms of some static varible. 

int main(void) 
{ 
void f(int x=70); // redeclaring function ::f 

f(); // prints f70 

g(); // prints g200 
para=500; 
g(); // prints g500 

{ 
void f(int x=700); // redeclaring function f 
f(); // prints f700 
::g(); // prints g500 
} 

::f(); // prints f7 !!!! 
// Note that earlier f() call in the same scope gave us f70!! 
// This shows that :: (scope resolution operator) forces compiler to 
// use global declaration with global signature's default value. 

{ 
void g(int x=100); // redeclaring function g 
g(); // prints g100!!! 
std::cout << "para = " << para << std::endl; // prints para = 500 
// Note that though value of para is unchaged local scope 
// changes value of default argument. 
} 
::g(); // prints g500 
return 0; 
} 

void f(int x) 
{ 
std::cout << "f" << x << std::endl; 
} 

void g(int x) 
{ 
std::cout << "g" << x << std::endl; 
} 

作爲一種編程指南,如果你需要,無論是redelcaring函數簽名或靜態變量的重新分配來改變默認參數的值,你最好不要使之成爲默認參數和保持一個簡單的論點。

0

它的要點:

1)設置一個static,非const變量。

2)將參數設置爲默認值爲該變量的值。

3)更改變量的值。

複印的