错误:C++需要所有声明的类型说明符

Error: C++ requires a type specifier for all declarations

本文关键字:声明 类型 说明符 C++ 错误      更新时间:2023-10-16

我是C++新手,我一直在读这本书。我读了几章,我想到了自己的想法。我尝试编译下面的代码,但出现以下错误:

||=== 构建:在密码中调试(编译器:GNU GCC 编译器)===| /Users/Administrator/Desktop/AppCreations/C++/Password/Password/main.cpp|5|error: C++需要所有声明的类型说明符| ||=== 构建 失败:1 个错误、0 个警告(0 分钟、2 秒)===|。

我不明白代码有什么问题,任何人都可以解释一下问题所在以及如何解决它吗?我阅读了其他帖子,但我无法理解它。

谢谢。

#include <iostream>
using namespace std;
main()
{
    string password;
    cin >> password;
    if (password == "Lieutenant") {
        cout << "Correct!" << endl;
    } else {
        cout << "Wrong!" << endl;
    }
}

你需要包含字符串库,你还需要为你的主函数提供一个返回类型,你的实现可能需要你为 main 声明一个显式的 return 语句(如果你没有显式提供一个,一些实现会添加一个隐式的;像这样:

#include <iostream>
#include <string> //this is the line of code you are missing
using namespace std;
int main()//you also need to provide a return type for your main function
{
    string password;
    cin >> password;
    if (password == "Lieutenant") {
        cout << "Correct!" << endl;
    } else {
        cout << "Wrong!" << endl;
    }
return 0;//potentially optional return statement
}

您需要声明 main 的返回类型。这应该始终在法律C++中int。在许多情况下,主线的最后一行将被return 0; - 即成功退出。除0以外的任何内容都用于指示错误条件。

一个额外的点

如果您尝试在类中分配变量,也可能会得到完全相同的错误。因为C++您可以在类中初始化变量,但在变量声明后无法稍后赋值,但是如果您尝试在类中定义的函数中赋值,那么它在C++中可以正常工作。