首页 > 解决方案 > 试图创建私有成员数组,其大小从 C++ 中的初始化列表给出(禁止使用)

问题描述

所以我试图在我的 School 班级上创建一个私有成员数组,我将在其中保存一些学生对象的地址。如果建筑物的容量允许的话,我的目标是模拟进入学校大楼的学生(想想小数字的问题) 我已经设法实现了“地址对象部分”,但我有一个关于大小的问题大批。给出数组大小的变量也是同一类的私有成员。话虽这么说,编译器给出了错误:

错误:非静态数据成员“School::class_capacity”的使用无效</p>

148 | 学生* pointer_array[class_capacity];

这是学校课程:

class School
{
    private:
      int class_capacity;
      Student* pointer_array[class_capacity];
   public:
        School(const int capacity)//constructor
      :class_capacity(capacity)
      {
        cout << "A New School has been created!" << endl;
      };
      ~School(){//destructor
        cout << "A School to be destroyed!" << endl;
      }; 
      void enter(Student* student, int stc=0/*student counter*/);
}

学生班级是:

class Student 
{
private:
    string name;
    int no_floor;
    int no_classroom;
public:
    Student(const string& nam,int no_fl,int no_cla)//constructor
    : name(nam), no_floor(no_fl), no_classroom(no_cla)
    {
      cout << "A new student has been created! with name " << name << " heading to floor: "<< no_floor << " class: " << no_classroom << endl;
    };

    ~Student()//destructor
    {
      cout << "A Student to be destroyed! with name " << name << " is at "<< " class: " << no_classroom;

    };

最后,我主要分配指向 Student 对象的指针数组。

int main(void)
{
//Student creation
       int i,floor,classroom;
       string stname;
       Student* students[5];
       for(i=0; i<5; i++)
       {
          cin >> stname;
          cin >> floor;
          cin >> classroom;
          students[i] = new Student(stname, floor, classroom);
       }
       for(i=0; i<5; i++)
       {
         delete students[i];
       }
}

以及输入功能码:

void School::enter(Student* student, int stc/*student counter*/)
{
  pointer_array[stc] = student;
  (pointer_array[stc])->print();
  cout << " enters school!" << endl;
}

我试图在 School 类中创建的数组是为了在我的主目录上保留一个指向已经创建的 Student 对象的指针。
有谁知道如何解决这个问题?再次禁止使用图书馆

标签: c++arraysclassoopobject

解决方案


如果不使用std::vector,您需要自己进行动态阵列管理

class School
{
private:
    int class_capacity;
    Student* students;
public:
    School(const int capacity)//constructor
      :class_capacity(capacity)
    {
        students = new Student[capacity];
        cout << "A New School has been created!" << endl;
    };

    ~School(){//destructor
        delete[] students;
        cout << "A School to be destroyed!" << endl;
    }; 

    // Disable copying to avoid accidental double-deletion of array
    School(School const&) = delete;
    School& operator=(School const&) = delete;
};

推荐阅读