如何將可選參數傳遞給C++中的方法? 任何代碼段...如何將可選參數傳遞給C++中的方法?
回答
這裏是傳遞模式可選參數的例子
void myfunc(int blah, int mode = 0)
{
if(mode == 0)
do_something();
else
do_something_else();
}
可以以兩種方式與這兩個呼叫MYFUNC有效
myfunc(10); //mode will be set to default 0
myfunc(10, 1);//mode will be set to 1
你能提供一些與字符串有關的例子嗎? – 2010-09-24 04:20:14
void myfunc(int blah,char mode [] = NULL) – 2010-09-24 04:28:27
NULL表示NULL指針,儘管它將被定義爲文字'0'。它不是常數零的通用名稱。對於整數(非指針),你應該使用數字:'int mode = 0'。 – UncleBens 2010-09-24 04:53:27
用逗號分隔它們,就像參數沒有默認值。
int func(int x = 0, int y = 0);
func(); // doesn't pass optional parameters, defaults are used, x = 0 and y = 0
func(1, 2); // provides optional parameters, x = 1 and y = 2
通常通過參數設置默認值:
int func(int a, int b = -1) {
std::cout << "a = " << a;
if (b != -1)
std::cout << ", b = " << b;
std::cout << "\n";
}
int main() {
func(1, 2); // prints "a=1, b=2\n"
func(3); // prints "a=3\n"
return 0;
}
個使用默認參數
template <typename T>
void func(T a, T b = T()) {
std::cout << a << b;
}
int main()
{
func(1,4); // a = 1, b = 4
func(1); // a = 1, b = 0
std::string x = "Hello";
std::string y = "World";
func(x,y); // a = "Hello", b ="World"
func(x); // a = "Hello", b = ""
}
注:以下是非法的構造
template <typename T>
void func(T a = T(), T b)
template <typename T>
void func(T a, T b = a)
一個重要的原則相對於默認參數的用法:
默認參數應在最右邊的末尾指出,一旦你指定默認值參數,則不能再次指定非默認參數。 例如:
int DoSomething(int x, int y = 10, int z) -----------> Not Allowed
int DoSomething(int x, int z, int y = 10) -----------> Allowed
這可能是有趣的,一些你在多個默認參數的情況:
void printValues(int x=10, int y=20, int z=30)
{
std::cout << "Values: " << x << " " << y << " " << z << '\n';
}
考慮下面的函數調用:
printValues(1, 2, 3);
printValues(1, 2);
printValues(1);
printValues();
以下輸出製作:
Values: 1 2 3
Values: 1 2 30
Values: 1 20 30
Values: 10 20 30
參考:http://www.learncpp.com/cpp-tutorial/77-default-parameters/
這就是我一直在尋找的。使用一個可以處理不同數量參數的函數。在頭文件中用默認值聲明函數,然後在沒有默認參數的情況下定義它,然後你就可以使用它。無需使功能過載 – 2016-10-27 01:57:29
- 1. 如何將可選參數傳遞給Ruby方法?
- 2. 將空參數傳遞給C#方法
- 3. 將可變參數傳遞給方法
- 4. 如何將C++的ref參數傳遞給c#方法?
- 5. 將C#中的數組參數傳遞給C++/CLI方法
- 6. 如何可變參數傳遞給在C#的內部方法
- 7. 如何將丟失的可選參數傳遞給PowerShell中的VBA方法
- 8. 如何將Scala數組傳遞給Scala可變參數方法?
- 9. 如何將字符串類型參數傳遞給C++方法
- 10. 將可空參數傳遞給Web方法C#
- 11. 將參數傳遞給方法的CakePHP
- 12. 將函數作爲參數傳遞給C++中的方法
- 13. 如何將可變參數傳遞給另一個方法?
- 14. 將可選參數傳遞給autofac
- 15. class_eval如何參數傳遞給方法
- 16. C# - 將所有方法參數傳遞給另一個方法?
- 17. 如何將可選的宏參數傳遞給函數
- 18. 如何將可選的閉包參數傳遞給函數?
- 19. 將C#枚舉傳遞給C++ CLI的包裝方法參數
- 20. 如何將參數傳遞給Rails中的委託方法
- 21. 如何將參數傳遞給NSTread中的方法?
- 22. 如何將參數傳遞給Groovy中的ant.java()方法
- 23. 如何將參數傳遞給eclipse中的main方法?
- 24. 如何將參數傳遞給Thread中的ThreadStart方法?
- 25. 將參數傳遞給方法 - UIPanGestureRecognizer
- 26. 將參數傳遞給Raphael customAttributes方法
- 27. JSF - 將參數傳遞給@PostConstruct方法
- 28. 將參數傳遞給a4j:ajax方法
- 29. 將參數傳遞給POST方法
- 30. 將參數傳遞給FB Api()方法
可能重複的[函數參數的默認值](http://stackoverflow.com/questions/2842928/default-value-of-function-parameter) – 2010-09-24 04:44:47
您不傳遞選項參數。你傳遞可選參數! – Chubsdad 2010-09-24 04:57:54
對於比保留哨兵值更加明確的控制,請查看boost :: optional <>。 – 2010-09-24 06:54:28