main()在C ++中是否已重载? [英] Is main() overloaded in C++?

查看:73
本文介绍了main()在C ++中是否已重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2个有效版本的main():

int main()  // version 1
int main(int argc, char **argv)  // version 2

但是两个重载不能同时存在.为什么不? (可能的用例:从终端运行程序时,如果未传递任何参数,则调用第一个版本,否则调用第二个版本.)

But both overloads cannot coexist at the same time. Why not? (Potential use case: while running the program from the terminal, if no arguments are passed the first version is called, otherwise the second version is.)

编译器是否执行特殊检查以使每个二进制文件仅允许一个版本?

Does the compiler perform a special check to allow just one version per binary?

推荐答案

§3.6.1/2(C ++ 03)说

§3.6.1/2 (C++03) says

实现不得预定义 main函数. 此功能应 不会超载. 返回类型为int的类型,否则返回 它的类型是实现定义的. 所有实现都应允许 以下main的定义:

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

   int main() { /* ... */ }
   int main(int argc, char* argv[]) { /* ... */ }

您可以使用它们中的任何一个.两者都符合标准.

You can use either of them. Both are standard compliant.

此外,由于char *argv[]等同于char **argv,所以用char **argv替换char *argv[]并没有什么区别.

Also, since char *argv[] is equivalent to char **argv, replacing char *argv[] with char **argv doesn't make any difference.

但是两个版本不能同时存在! (用例可能是这样的:在命令提示符下运行二进制文件时,如果不传递任何参数,则应将第一个版本称为第二个版本.)

But both the versions cannot co-exist at the same time ! (use case can be like: while running the binary from command prompt, if you pass no argument then 1st version should be called else the 2nd version).

不.两种版本不能同时共存.一个程序可以只具有一个main函数.哪一个,取决于您的选择.如果要处理命令行参数,则必须选择第二个版本,否则第一个版本就足够了.另请注意,如果您使用第二个版本,并且不传递任何命令行参数,则其中没有任何危害.它不会引起任何错误.您只需要相应地解释argcargv,并根据它们的值,就可以编写程序的逻辑和流程.

No. Both versions cannot co-exist at the same time. One program can have exactly one main function. Which one, depends on your choice. If you want to process command-line argument, then you've to choose the second version, or else first version is enough. Also note that if you use second version, and don't pass any command line argument, then there is no harm in it. It will not cause any error. You just have to interpret argc and argv accordingly, and based on their value, you've to write the logic and the flow of your program.

这篇关于main()在C ++中是否已重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆