Naw*_*waz 14 c++ standards program-entry-point overloading
由于C+++允许函数重载,我们可以重载main()吗?
例如,
int main(const std::string &)
{
return 0;
}
int main(int argc, char *argv[])
{
return main("calling overloaded main");
}
Run Code Online (Sandbox Code Playgroud)
gcc-4.3.4不编译这个,并给出这些错误:(见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*转换无效'
to'int'prog.cpp:8:错误:函数'int main(int,char**)'
prog.cpp的参数太少:10:错误:此时在文件中
所以我想知道C++标准是否明确禁止重载main?如果是这样,哪个陈述?
Joh*_*itb 26
是的,它明确禁止这样做.参见3.6.1p2
实现不应预定义主函数.此功能不应过载.
这样,主函数的名称可以保持不变.也就是说,运行时库可以调用具有固定名称(例如main或_main)的符号来跳转到主函数.库的代码不需要依赖于程序main函数的参数列表.
该实现还允许为该main函数定义其他有效参数列表(例如,POSIX规范指定了char **env环境变量的参数).当过载main是"非主要功能"或者它是否是"主要功能" 时是不明确的,因此是一个切入点.据推测,如果您要声明多个入口点,您会想要收到错误,因此这些问题很重要.