C++重载函数调用自身的版本,带有更多参数

Ale*_*nto 3 c++ overloading

我使用函数重载来获得行为的一般版本和更常见的版本.通常的函数只选择实际依赖于第一个参数的第二个参数的默认值,并且编译器给我一个错误,因为它甚至不能识别第二个函数的存在.我也尝试使用默认值,但由于默认值取决于第一个参数,编译器似乎不接受它.

因此,这里只是用于说明的简化示例.功能重载案例:

#include <stdio.h>  
struct pair {
  int x;
  int y;
};

int func(pair a){
  return func(a, a.y);
}

int func(pair a, int b) {
  return a.x*b;
}

int main() {
  pair z;
  z.x = 2;
  z.y = 4;
  printf("%d\n", func(z));
  printf("%d\n", func(z,12));
}
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

a.c: In function ‘int func(pair)’:
a.c:9:21: error: too many arguments to function ‘int func(pair)’
a.c:8:5: note: declared here"
Run Code Online (Sandbox Code Playgroud)

默认值示例:

#include <stdio.h>

struct pair {
  int x;
  int y;
};


int func(pair a, int b = a.y) {
  return a.x*b;
}
int main() {
     pair z;
     z.x = 2;
     z.y = 4;
     printf("%d\n", func(z));
     printf("%d\n", func(z,12));
}
Run Code Online (Sandbox Code Playgroud)

给我以下错误:"本地变量a可能不会出现在此上下文中"

那么,在C++中有没有办法模仿这种行为?我从未在其他语言中遇到过这个问题,比如Java甚至是ASP.

谢谢你们.

Val*_*ade 5

在C和C++中,在函数调用之前,应该声明或定义该函数.在这里您正在调用return func(a, a.y);但该函数func(pair, int)尚未声明或定义.

您需要更改这两个函数的定义,或者只是在代码的开头声明函数.正如其他答案解释了第一种方法,这里是第二种方法的片段.

  #include <stdio.h> 
  //Function Declaration
  int func(pair);
  int func(pair, int); 
  struct pair {
      int x;
      int y;
  };

  int func(pair a){
       return func(a, a.y);
  }

  int func(pair a, int b) {
      return a.x*b;
  }

  int main() {
      pair z;
      z.x = 2;
      z.y = 4;
      printf("%d\n", func(z));
      printf("%d\n", func(z,12)); 
  }
Run Code Online (Sandbox Code Playgroud)