我使用默认参数不正确吗? [英] Am I using default arguments incorrectly?

查看:99
本文介绍了我使用默认参数不正确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习C ++的初学者书。我有一些java经验(但是说过,我从来没有使用在java中的默认参数是诚实的)

I've just started going through a beginners book of C++. I have some java experience (but having said that, I've never used default arguments in java to be honest)

所以,如上所述,我的问题是与默认参数..

So, as mentioned, my issue is with default arguments..

这是我使用的代码段:

#include <iostream>

using namespace std;

//add declaration
int add(int a, int b);

int main (void)
{
        int number1;

        cout << "Enter the first value to be summed: ";
        cin >> number1;
        cout << "\nThe sum is: " << add(number1) << endl;
}

int add(int a=10, int b=5)
{
        return a+b;
}

我从g ++编译器得到的响应是: int add(int,int)'

The response I get from g++ compiler is: "too few arguments to function 'int add(int, int)'

我这样做是错误的(我也尝试过文字参数)

Am I doing this wrong? (I've also tried it with literal arguments)

PS我似乎无法获得正确显示的代码段。系统是否已更改?

P.S. I can't seem to get the code snippet to display properly? Has the system changed?

推荐答案

//add declaration
int add(int a=10, int b=5);


int add(int a, int b)
{
   return a+b;
}




§8.3.6默认参数
默认参数只能在
函数声明的参数声明子句或
模板参数。不能为
参数包指定默认参数。

§ 8.3.6 Default arguments A default argument shall be specified only in the parameter-declaration-clause of a function declaration or in a template-parameter. A default argument shall not be specified for a parameter pack.

这篇关于我使用默认参数不正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆