小编Ale*_*nto的帖子

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

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

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

#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 = …
Run Code Online (Sandbox Code Playgroud)

c++ overloading

3
推荐指数
1
解决办法
1842
查看次数

标签 统计

c++ ×1

overloading ×1