详谈C与C++的函数声明中省略参数的不同意义

时间:2022-02-12 08:24:43

一直都以为C/C++中形如

?
1
int func();

这样的函数声明其意义就是一个参数 void(没有参数)的函数。然而今天在看C++的时候突然看到这么一句:

?
1
2
3
对于带空参数表的函数,C和C++有很大的不同。在C语言中,声明
int func2();
表示“一个可带任意参数(任意数目,任意类型)的函数”。这就妨碍了类型检查。而在C++语言中它就意味着“不带参数的函数”。

这一点老师并没有讲到,学校教科书里也没有提到,带着好奇心,我特意试了一下

test.c

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
 
void fun();
int main()
{
  fun(1, 1);
 
  return 0;
}
 
void fun(int a, int b)
{
  printf("%d\n", a+b);
}
?
1
2
3
编译通过
$ gcc -Wall test.c -o test
$ ./test 2
?
1
2
3
4
5
6
7
8
9
$ mv test.c test.cpp
$ g++ -Wall test.cpp -o test
test.cpp: 在函数‘int main()'中:
test.cpp:6:10: 错误:too many arguments to function ‘void fun()'
 fun(1, 1);
 ^
test.cpp:3:6: 附注:在此声明
 void fun();
   ^~~

这也解释了为什么主函数要写成这样的原因

?
1
int main(void)

以上这篇详谈C与C++的函数声明中省略参数的不同意义就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/lymboy/archive/2017/11/16/7846588.html