300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > c++函数参数默认值设置

c++函数参数默认值设置

时间:2020-06-24 01:03:47

相关推荐

c++函数参数默认值设置

c++函数参数默认值设置

1,函数参数默认值在函数声明的参数列表上定义,函数定义不变;

#include <iostream>using namespace std;int add(int a = 0, int b = 0, int c = 0);int main(){std::cout << add(1, 2, 3) << std::endl;getchar();return 0;}int add(int a, int b, int c){return a + b + c;}

2,参数列表可以全部设置为默认值,也可部分设置为默认值,只能从右到左逐个设置

(1) 从要设置的那个参数开始,如果右侧参数没有全部设定默认值,则会报错;

#include <iostream>using namespace std;int add(int a = 0, int b, int c);int main(){std::cout << add(1, 2, 3) << std::endl;getchar();return 0;}int add(int a, int b, int c){return a + b + c;}

c:\desk\test\test\test.cpp(4) : error C2548: 'add' : missing default parameter for parameter 21>c:\desk\test\test\test.cpp(4) : error C2548: 'add' : missing default parameter for parameter 3

(2)正确设置部分默认值

#include <iostream>using namespace std;int add(int a , int b = 0, int c = 0);int main(){std::cout << add(1, 2, 3) << std::endl;getchar();return 0;}int add(int a, int b, int c){return a + b + c;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。