我们可以在C ++中重载main()函数吗? [英] Can we overload main() function in C++?
问题描述
由于C ++++允许函数重载,所以我们可以重载main()
吗?
Since C+++ allows function overloading, can we overload main()
?
例如,
int main(const std::string &)
{
return 0;
}
int main(int argc, char *argv[])
{
return main("calling overloaded main");
}
gcc-4.3.4
不会编译它,并产生以下错误:(请参见 ideone )
gcc-4.3.4
doesn't compile this, and gives these errors: (see at ideone)
prog.cpp:4:错误:"int main(const std :: string&)"的第一个参数应为"int"
prog.cpp:4:错误:"int main(const std :: string&)"仅接受零个或两个参数
prog.cpp:在功能‘int main(int,char **)’中:
prog.cpp:8:错误:C函数"int main(int,char **)"的声明与
相冲突 prog.cpp:4:错误:此处先前的声明"int main(const std :: string&)"
prog.cpp:在功能‘int main(int,char **)’中:
prog.cpp:10:错误:从'const char *'到'int'的无效转换
prog.cpp:8:错误:函数'int main(int,char **)'的参数太少了
prog.cpp:10:错误:文件
prog.cpp:4: error: first argument of ‘int main(const std::string&)’ should be ‘int’
prog.cpp:4: error: ‘int main(const std::string&)’ takes only zero or two arguments
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:8: error: declaration of C function ‘int main(int, char**)’ conflicts with
prog.cpp:4: error: previous declaration ‘int main(const std::string&)’ here
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:10: error: invalid conversion from ‘const char*’ to ‘int’
prog.cpp:8: error: too few arguments to function ‘int main(int, char**)’
prog.cpp:10: error: at this point in file
所以我想知道C ++标准是否明确地禁止main
的重载?如果是,那是哪条语句?
So I'm wondering if the C++ Standard explicitly forbids overloading of main
? If so, which statement?
推荐答案
是的,它明确禁止这样做.请参阅3.6.1p2
Yes it explicitly forbids that. Refer to 3.6.1p2
实现不应预定义主要功能.此功能不得重载.
An implementation shall not predefine the main function. This function shall not be overloaded.
这样,主函数的名称可以保持不变.也就是说,运行时库可以调用具有固定名称(例如main
或_main
)的符号来跳转到主函数.库的代码将不必依赖于程序的main
函数具有的参数列表.
This way, the main function's name can stay unmangled. That is, the runtime library can call a symbol having a fixed name (e.g main
or _main
) to jump to the main function. The libraries' code will not need to depend on what parameter list the program's main
function has.
还允许实现为main
函数定义其他有效的参数列表(例如,POSIX规范为环境变量指定char **env
参数). main
的重载是非主函数"还是主函数"(即入口点),尚不清楚.据推测,如果您声明多个入口点,您将希望得到一个错误,因此此类问题很重要.
The implementation is also allowed to define additional valid parameter lists for the main
function (The POSIX spec specifies a char **env
parameter for the environment variables, for example). It would not be clear when an overload of main
is a "non-main function" or whether it's a "main function", thus an entry point. Presumably, you would want to get an error if you would declare more than one entry point, so such issues are important.
这篇关于我们可以在C ++中重载main()函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!