类与对象的简单改错 求解释谢谢

#include <iostream>
using namespace std;
#include <iomanip>
#include <cstring>
//student.h
class Student
{
	public:
		Student(char *);
		~Student();
		void displayGrades();
		Student addGrade(int);
		static int getNumStudents();
	private:
		int *grades;
		char *name;
		int numGrades;
		//int idNum;
		static int numStudents;
};
//student.cpp
static int numStudents = 0;
Student::Student(char *nPtr) 
{
	grades= new int[1];				//Id returned 1 exit status是怎么回事 
	grades[0]=0;
	name=new char[strlen(nPtr)+1];
	strcpy(name, nPtr);
	numGrades = 0;
	numStudents++;
	cout<<"A student has been added"<<endl;
}
Student::~Student()
{
	cout<<*name<<" has been deleted"<<endl;
	delete[] grades;
	delete[] name;
	numStudents--;
}
void Student::displayGrades()
{
	cout<<"Here are the grades for "<<name <<endl;
	for (int i=0; i<numGrades;i++)
		cout<<setw(5)<<grades[i];
	cout<<endl<<endl;	
}
Student Student::addGrade(int grade)
{
	int * temp = new int[numGrades+1];
	for (int i=0; i<numGrades; i++)
		temp[i]=grades[i];
	temp[ numGrades ]=grade;
	grades=temp;
	numGrades++;
	return *this;
}
int Student::getNumStudents()
{
	return numStudents;
}
//debug.cpp
int main()
{
	cout<<"There are currently "<<Student::getNumStudents()<<" students" <<endl<<endl;
	Student *s1Ptr = new Student("Student 1");      //为啥总提示不建议使用从字符串常量转换到char 
	s1Ptr->addGrade(100).addGrade(75).addGrade(89);
	s1Ptr->displayGrades();
	//(*s1Ptr).displayGrades();
	Student *s2Ptr = new Student("Student 2");
	s2Ptr->addGrade(83).addGrade(92);
	s2Ptr->displayGrades();
	Student s3("Student 3");
	s3.addGrade(62).addGrade(91);
	s3.displayGrades();
	cout<<"There are currently "<<Student::getNumStudents()<<" students"<<endl<<endl;
	delete[] s2Ptr;
	delete[] s1Ptr;
	return 0;
}

 

参考GPT和自己的思路:

在代码中,出现了一些语法错误。

首先,在第25行,分配内存时应该为 grades = new int[1],而不是 grades= new int 。这是因为 grades 是一个指向整数数组的指针,因此需要指定其大小。

其次,在第33行,析构函数的输出应该使用 name 指针,而不是解引用它。正确的语法应该是 cout<< name <<" has been deleted"<<endl;。

最后,在第65行,传递字符串常量会导致警告。为了避免这个问题,应该使用 const char* 而不是 char*。

希望这可以帮助您更好地理解类和对象的概念。

参考GPT和自己的思路:

在类的定义中,addGrade() 函数应该返回一个指向 Student 对象的指针,而不是一个 Student 对象本身。因此,其函数声明应该如下:

Student* addGrade(int);

同时,在 addGrade() 函数中,在扩展数组时,需要先删除原先分配的内存,然后再重新分配才能实现真正的数组扩展。

修改后的 addGrade() 函数的代码如下:

Student* Student::addGrade(int grade)
{
    int *temp = new int[numGrades + 1];
    for (int i = 0; i < numGrades; i++)
        temp[i] = grades[i];
    temp[numGrades] = grade;
    delete[] grades; // 先释放原先分配的内存
    grades = temp;
    numGrades++;
    return this;
}

参考GPT和自己的思路:

问题1:“Id returned 1 exit status是怎么回事?”
解释:这个错误是因为在代码中使用了new关键字动态申请内存,但是申请内存的数量为0,导致程序崩溃。应该在动态申请内存时,根据实际需要申请足够的内存空间。

问题2:“为啥总提示不建议使用从字符串常量转换到char?”
解释:这个警告是由于在代码中使用了一个字符串常量来初始化一个char类型的指针。字符串常量的地址是固定的,而指针可以改变指向,在使用时可能会导致不必要的错误。建议使用std::string或者使用strcpy函数来初始化char类型的指针。