+ -
当前位置:首页 → 问答吧 → 关于默认参数的问题

关于默认参数的问题

时间:2010-10-01

来源:互联网

看c++ primer的时候 它说  
既可以在函数声明也可以在函数定义中指定默认参数

我在声明的时候默认没有错 在定义的时候默认就出错了啊 
C/C++ code

#include<iostream>
using namespace std;
int f(int a,int b);
int main()
{
    cout<<f();

}
int f(int a=2,int b=3)
{
    return a+b;
}


这个定义的默认参数 貌似不管用啊

作者: djh512   发布时间: 2010-10-01

我记得是只能在声明中指定。

ps:顺便测试一下插入代码
C/C++ code
#include<iostream>
using namespace std;
int f(int a,int b);

作者: falcomavin   发布时间: 2010-10-01

引用楼主 djh512 的回复:
看c++ primer的时候 它说
既可以在函数声明也可以在函数定义中指定默认参数

我在声明的时候默认没有错 在定义的时候默认就出错了啊

C/C++ code

#include<iostream>
using namespace std;
int f(int a,int b);
int main()
{
cout<<f();

}
int f(in……
using namespace int f(int a,int b);看下!

作者: ganpengjin1   发布时间: 2010-10-01

我测试的貌似也是只能在声明中默认

作者: djh512   发布时间: 2010-10-01

默认参数只能在声明的时候指定
也就是这个模式才是对的:
C/C++ code
void f(int a, int b=3);
int main()
{
    f(2);
    return 0;

}

void f(int a, int b/* =3 */)
{
    cout<<b;
}

作者: ayw215   发布时间: 2010-10-01

LZ:应该是你的理解问题,C++ Primer没有明确指出“既可以在函数声明也可以在函数定义中指定默认参数”,而它指出默认参数只能在一个文件中被指定一次,如果在函数定义中指定,则只能用在包含该函数定义的源文件的函数调用中。

作者: gules   发布时间: 2010-10-01

指定默认实参的约束
We can specify default argument(s) in either the function definition or declaration. However, a parameter can have its default argument specified only once in a file. The following is an error:

既可以在函数声明也可以在函数定义中指定默认实参。但是,在一个文件中,只能为一个形参指定默认实参一次。下面的例子是错误的:

  // ff.h
  int ff(int = 0);

  // ff.cc
  #include "ff.h"
  int ff(int i = 0) { /* ... */ } // error



 Default arguments ordinarily should be specified with the declaration for the function and placed in an appropriate header.

通常,应在函数声明中指定默认实参,并将该声明放在合适的头文件中。
 

If a default argument is provided in the parameter list of a function definition, the default argument is available only for function calls in the source file that contains the function definition.

如果在函数定义的形参表中提供默认实参,那么只有在包含该函数定义的源文件中调用该函数时,默认实参才是有效的。

作者: poiu710   发布时间: 2010-10-01

primer上说是声明在头文件,定义在另一个文件是两个文件上的。所以“既可以在函数声明也可以在函数定义中指定默认实参”这是对的,LZ你是将声明和定义放在一个文件中了,这是primer作者没有想到的。
下面这样就对了。
Untitled1.h
C/C++ code

#ifndef UNT__H
#define UNT__H
int f(int a,int b);
#endif


Untitled1.cpp
C/C++ code

#include <iostream>
#include "Untitled1.h"
using namespace std;

int f(int a=2, int b=3)
{
    cout<< a+b << endl;
    return 0;
}

int main()
{
    f(2);
    system("pause");
    return 0;
}


作者: poiu710   发布时间: 2010-10-01

热门下载

更多