错误:‘::main’必须返回‘int’ [英] error: ‘::main’ must return ‘int’

查看:39
本文介绍了错误:‘::main’必须返回‘int’的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在课堂上使用 Putty 虚拟机 (UNIX),我们正在做一个简短的 C++ 作业.任务是:创建一个 C++ 程序来测试文件帐户是否存在并打印一条消息来说明文件是否存在"

这就是我所拥有的,但是当我尝试编译代码时,出现此错误:错误:‘::main’必须返回‘int’

#include#include使用命名空间标准;内联 bool exists_test1 (const std::string& name) {if (FILE *file = fopen(name.c_str(), "r")) {fclose(文件);返回真;} 别的 {返回假;}}无效主(){字符串 s;cout<<"输入文件名";cin>s;bool ans =exists_test1(s);如果(答案){cout<<文件存在"<<endl;}别的{cout<<"文件不存在";}}

解决方案

main 的返回类型为 int.这是由 C++ 标准定义的.在我的 C++11 草案的本地副本中,它在 § 3.6.1 Main Function 中进行了概述:

<块引用>

  1. 一个实现不应预定义主函数.该函数不得重载.它应该有一个int类型的返回类型,否则它的类型是实现定义的.所有实现都应该允许main的以下两个定义:

    int main() {/* ... */}

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

因此,根据标准,您的程序格式不正确,您的编译器正确地将其报告为错误.将您的函数定义为:

int main(){//你的代码...返回0;}

I am currently using Putty virtual machine (UNIX) for my class, and we are doing a short C++ assignment. The assignment is to: "Create a C++ program that tests to see if the file accounts exists and prints a message to say whether the file exists"

This is what I have, but when I try to compile the code, I get this error: error: ‘::main’ must return ‘int’

#include<iostream>
#include<fstream>

using namespace std;
inline bool exists_test1 (const std::string& name) {

if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}

void main()
{
string s;
cout<<"Enter filename";
cin>>s;
bool ans =exists_test1(s);
if(ans)
{
cout<<"File Exist"<<endl;
}
else
{
cout<<"File Does not Exist";
}
}

解决方案

The return type of main is int. This is defined by the C++ standard. In my local copy of the C++11 draft it's outlined in § 3.6.1 Main Function :

  1. 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() { /* ...  */ }
    

    and

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

Therefore your program is ill-formed according to the standard, and you compiler is rightly reporting it as an error. Define your function instead as:

int main()
{
    // your code...

    return 0;
}

这篇关于错误:‘::main’必须返回‘int’的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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