我收到有关无效使用非静态成员以及结构成员无法正常工作的其他问题的错误,我无法理解问题所在,谢谢。

#include <iostream>
#include <string>
using namespace std;


struct classroom {
int RoomNumber;
int NumberOfChairs;
int NumberOfStudents;
int ListOfStudents[NumberOfStudents];
string LectureName;
bool Window, Projector, Available;
}classroom;




int main() {

cout << "Please enter your room number" << endl;
cin >> classroom.RoomNumber;
cout << "Enter the name of the Lecture" << endl;
cin >> classroom.LectureName;
cout << "Enter  number of students" << endl;
cin >> classroom.NumberOfStudents;
cout << "Enter " << classroom.NumberOfStudents <<  " Student Names" << endl;
cin >> classroom.ListOfStudents;
cout << "Enter number of chairs" << endl;
cin >> classroom.NumberOfChairs;
cout << "Are there any Windows? (Y/N)" << endl;
cin >> classroom.Window;
cout << "Are there any Projectors? (Y/N)" << endl;
cin >> classroom.Projector;
cout << "Are there any Available? (Y/N)" << endl;
cin >> classroom.Available;

    return 0;
}

错误
prog.cpp:10:5: error: invalid use of non-static data member ‘classroom::NumberOfStudents’
 int NumberOfStudents;
     ^
prog.cpp:11:20: error: from this location
 int ListOfStudents[NumberOfStudents];
                    ^
prog.cpp: In function ‘int main()’:
prog.cpp:28:18: error: ‘struct classroom’ has no member named ‘ListOfStudents’
 cin >> classroom.ListOfStudents;
                  ^

最佳答案

除非int ListOfStudents[NumberOfStudents]的类型为NumberOfStudents,否则不能声明数组const int。如果它是变量(即不是const),则编译器不知道如何为数组分配空间。因此,只需将int NumberOfStudents;更改为const int NumberOfStudents;即可。但是,当您执行此操作时,您的结构也将期望NumberOfStudents是静态的,因此您实际上需要编写static const int NumberOfStudents;

此时,您将无法cin >> classroom.NumberOfStudents,事情变得很丑陋。我假设这不是您想要的。

如果您确实想要一个可变大小的数组,那么执行此操作的标准方法是使用堆分配。换句话说,您需要声明ListOfStudents为指向整数数组的指针,该整数数组将在运行时分配。

也就是说,您要按以下方式更改结构:

struct classroom {
int RoomNumber;
int NumberOfChairs;
int NumberOfStudents;
int* ListOfStudents;
string LectureName;
bool Window, Projector, Available;
}classroom;

然后在main函数内(或实际上,在任何您喜欢的地方),您都需要调用new来分配一些空间。像这样:
classroom.ListOfStudents = new int[classroom.NumberOfStudents];

最后一点:这样做,您还需要将cin >> classroom.ListOfStudents;更改为一个循环,该循环会将所有值读入数组。像这样:
for (int i=0; i < classroom.NumberOfStudents; i++) {
  cin >> classroom.ListOfStudents[i];
}

正如其他答案所建议的那样,更改变量classroom的名称以使其与结构的名称不匹配也是一个好主意。但是,它仍然应该可以正常编译(我已经对其进行了测试)。只是有点困惑。

09-30 23:34