错误:C++需要所有声明的类型说明符
Error: C++ requires a type specifier for all declarations
我是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++中可以正常工作。
相关文章:
- std::enable_if 更改成员 *变量* 声明/类型
- 对前向声明类型进行unique_ptr的解决方法
- 如何将声明类型作为参数发送
- 在 Fortran 中泛化特定声明类型的操作
- 使用 (c++11) 声明类型时放置 __declspec(dllimport) 关键字的位置
- 模板函数可以使用带有删除的构造函数的声明类型
- 声明类型没有任何可变类型
- 如何使用声明类型简化此代码
- 使用声明类型选择函数专业化
- 替代班级内声明类型的别名
- 对于自动键入推论的参数,声明类型(自动)应推导的内容
- 使用 decltype 的条件声明类型
- 您如何声明类型结构的堆栈?在C 中
- 将指向前向声明类型的指针推送到 typedef'd 向量时出现编译器错误
- 声明适用于 auto,但不能显式声明类型?
- 声明类型包含未展开的参数包'Args'
- 课堂上的Typedef.在另一个类错误中:尚未声明类型
- 冲突的声明类型/价值不匹配
- 获取具有AST访问者clang的功能声明类型
- 变量声明类型定义 C 中的约定