gpt4 book ai didi

c++ - 尝试创建私有(private)成员数组,其大小从 C++ 中的初始化列表给出( 使用被禁止)

转载 作者:行者123 更新时间:2023-12-03 07:22:02 24 4
gpt4 key购买 nike

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

error: invalid use of non-static data member ‘School::class_capacity’

148 | Student* pointer_array[class_capacity];


这是学校类(class):
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)是:
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 对象的指针。
有谁知道如何解决这个问题?再次禁止使用图书馆

最佳答案

不使用 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;
};

关于c++ - 尝试创建私有(private)成员数组,其大小从 C++ 中的初始化列表给出(<vector> 使用被禁止),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64807731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com