所以我的目标是创建同一类的许多对象,而无需多次复制一个对象。我想我通过创建一个指向某个对象的指针数组找到了一种方法,但是我遇到了段错误。
不幸的是,在我尝试做的这个项目中,除了 <cstring>
之外,我没有使用任何其他库。 (我必须在这里补充一点,类的构造函数有一些参数作为输入)。
想法?
这是代码:
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
int i, floor, classroom; //the floor of the school and the classroom the student is heading to
char *stname;
typedef Student *stptr;
stptr *students = new stptr[15];
for (i = 0; i < 15; i++)
{
cin >> stname;
cin >> floor;
cin >> classroom;
students[i] = new Student(stname, floor, classroom);
}
}
...以及类(class)的代码:class Student
{
private:
char *name;
int no_floor;
int no_classroom;
public:
Student(const char *nam, int no_fl, int no_cla) //constructor
{
name = new char[strlen(nam + 1)];
strcpy(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 floor: " << no_floor << " class: " << no_classroom;
delete[] name;
};
};
最佳答案
我建议不要使用这种指针混淆:
Student** students = new Student*[15];
更容易理解 IMO。您可以使用 C++ 提供的工具来自动处理对象的字符串数组:
std::string
对于字符串;std::vector
为数组。对象指针在多态的上下文中可能很有用,但即便如此,最好使用 smart pointers .
如pointed out by marcinj in the comments
name
声明也需要修复。还有pointed out by Alan Birtles您正在使用
stname
未初始化,这可能是段错误的罪魁祸首。要修复您的代码,使用您当前使用的工具,您应该执行类似于以下代码的操作,请注意,除了修复之外,rule of three必须尊重:
#include <iostream>
#include <cstring>
class Student {
char *name;
int no_floor;
int no_classroom;
public:
Student(const char *nam, int no_fl, int no_cla){//constructor
name = new char[strlen(nam) + 1];
strcpy(name, nam);
no_floor = no_fl;
no_classroom = no_cla;
std::cout << "A new student has been created! with name " << name << " heading to floor: " << no_floor << " class: " << no_classroom << std::endl;
};
~Student(){//destructor
std::cout << "A Student to be destroyed! with name " << name << " is at floor: " << no_floor << " class: " << no_classroom;
delete [] name;
};
Student (const Student& student) { //copy constructor
this->name = nullptr;
*this = student;
}
Student& operator = (const Student& student){ //assignment operator
if(this == &student){
return *this;
}
delete [] this->name;
this->name = new char[strlen(student.name) + 1];
strcpy(this->name, student.name);
this->no_classroom = student.no_classroom;
this->no_floor = student.no_floor;
return *this;
}
};
int main(){
int i, floor, classroom;
char *stname = new char[100];
typedef Student *stptr;
stptr *students = new stptr[15];
for (i = 0; i < 15; i++){
std::cin >> stname;
std::cin >> floor;
std::cin >> classroom;
students[i] = new Student(stname, floor, classroom);
}
delete [] stname;
for (i = 0; i < 15; i++){
delete students[i];
}
//or for the deletion in inverse order
//for (i = 2; i >= 0; i--){
// delete students[i];
//}
delete [] students;
}
关于c++ - 尝试在不使用 vector 的情况下在 C++ 中创建同一类的许多对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64750901/