错误:'[' 之前预期的非限定 id 和错误:'users'未在此范围内声明

ERROR: expected unqualified-id before '[' and ERROR: 'users' was not declared in this scope

本文关键字:错误 users 范围内 声明 id      更新时间:2023-10-16

我试图制作一个程序,您可以在其中写入登录名和密码,并且,如果用户存在于类中,它会显示权限(例如Carl可以读取和执行文件(。现在我有两个错误:

22:9: error: expected unqualified-id before '[' token
36:23: error: 'users' was not declared in this scope

我是 c++ 的新手,所以我不确定我该怎么办。谁能帮忙?

#include <iostream>
using namespace std;
int main()
{
class User {
public:
string login;   
string password;
bool R;
bool W;
bool X;
User() = default;
User(string login, string password, bool r, bool w, bool x);
};
//setlocale(LC_ALL, "Russian");
string login, password;
string User[] users = new User[]
{
new User("Alice", "Cooper", false, true, true),
new User("Bob", "Dylan", false, true, false),
new User("Carl", "Perkins", true, false, true)
};
cout << "nEnter login: " << endl;
cin >> login;
cout << "nEnter password: " << endl;
cin >> password;
bool userFound = false;
User user = users[i];
for (int i=0; i < users.Length; i++)
{
if (user.login == login && user.password == password)
{
userFound = true;
cout << "nCan read: " << user.R;
cout << "nCan write: " << user.W;
cout << "nCan execute: " << user.X;
break;
}
}
if (!userFound)
{
cout << "nUser not found" << endl;
}
}
string User[] users = new User[]
{
new User("Alice", "Cooper", false, true, true),
new User("Bob", "Dylan", false, true, false),
new User("Carl", "Perkins", true, false, true)
};

这C++无效(看起来您以某种方式混合了C++和 Java 语法(。首先,您在声明中意外地string(并且您没有声明string- 您需要#include <string>!其次,C 数组声明如下:

Type var[N];

第三,你不能用指针初始化 C 数组(从new返回(。

第四,new Type[]需要数组大小

第五,你不能用指针初始化一个User数组(new User创建一个User*(。

所有这些问题都可以通过使用std::vector来解决:

std::vector<User> users{
User("Alice", "Cooper", false, true, true),
User("Bob", "Dylan", false, true, false),
User("Carl", "Perkins", true, false, true)
};