【问题标题】:c++ default function parameter dont work [duplicate]c ++默认函数参数不起作用[重复]
【发布时间】:2015-03-09 06:49:48
【问题描述】:

我有一个需要默认参数的函数:

LINE 13:
    void genRand(double offset_x = 0.0, double offset_y = 0.0);

这是函数:

LINE 84:
    void game::genRand(double offset_x = 0.0, double offset_y = 0.0) {
        perlin.SetFrequency(0.1);
        for(int _x=0; _x<dimensions.x/32; _x++){
            for(int _y=0; _y<dimensions.y/32; _y++){
                vec.push_back((perlin.GetValue(_x+offset_x, _y+offset_y, 0.2)+1.f)*2/2);
            }
        }
    }

错误:

make
g++ main.cpp -w -std=c++11 -lsfml-graphics -lsfml-window -lsfml-system -lnoise -o main
main.cpp:84:64: error: default argument given for parameter 1 of ‘void game::genRand(double, double)’ [-fpermissive]
 void game::genRand(double offset_x = 0.0, double offset_y = 0.0) {
                                                                ^
main.cpp:13:14: note: previous specification in ‘void game::genRand(double, double)’ here
         void genRand(double offset_x = 0.0, double offset_y = 0.0);
              ^
main.cpp:84:64: error: default argument given for parameter 2 of ‘void game::genRand(double, double)’ [-fpermissive]
 void game::genRand(double offset_x = 0.0, double offset_y = 0.0) {
                                                                ^
main.cpp:13:14: note: previous specification in ‘void game::genRand(double, double)’ here
         void genRand(double offset_x = 0.0, double offset_y = 0.0);
              ^

我不明白我做错了什么。

【问题讨论】:

  • 从函数定义中删除默认值。您只需要在声明中使用它们。
  • 您只在声明中指定默认参数,而不是在定义中(除非它是内联的)。
  • 默认参数只在声明中,当你定义和实现函数时编译器已经知道值应该是什么(作为函数本身,你只知道你得到了一个值,变量总是在那里)...

标签: c++ default-arguments


【解决方案1】:

单独写函数(体)的定义时,不要再带default parameter了。

事实上,默认参数值必须出现在声明中,因为这是调用者看到的唯一内容。

最好在重复的函数参数列表中注释默认值:

void foo(int x = 42,
         int y = 21);

void foo(int x /* = 42 */,
         int y /* = 21 */)
{
   ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-23
    • 2014-02-10
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多