Am I using default arguments incorrectly?

≡放荡痞女 提交于 2019-12-23 07:29:05

问题


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..

This is the code snippet I'm using:

#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;
}

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)

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


回答1:


It's the other way around

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


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

§ 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.



来源:https://stackoverflow.com/questions/13713916/am-i-using-default-arguments-incorrectly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!