【问题标题】:Error: C++ requires a type specifier for all declarations错误:C++ 需要所有声明的类型说明符
【发布时间】:2015-01-27 03:32:56
【问题描述】:

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

||=== 构建:密码调试(编译器:GNU GCC 编译器)===| /Users/Administrator/Desktop/AppCreations/C++/Password/Password/main.cpp|5|错误: 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;
    }

}

【问题讨论】:

  • 你还需要一个#include &lt;string&gt;
  • @Gigabillion 请不要编辑您的问题以包含答案。这让尚未阅读该问题的人感到困惑。相反,请单击已发布答案之一旁边的“打勾”标记以表明您接受该答案。

标签: c++ compiler-errors codeblocks specifier


【解决方案1】:

你需要包含字符串库,你还需要为你的 main 函数提供一个返回类型,你的实现可能需要你为 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
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • return 0 对于main 总是隐含的。
    【解决方案3】:

    加分

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-09
      • 2017-06-05
      • 1970-01-01
      • 2018-03-01
      • 2022-11-14
      相关资源
      最近更新 更多