m0_56926947 2021-06-08 23:16 采纳率: 0%
浏览 20

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

#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;
}
  • 写回答

3条回答 默认 最新

  • 「已注销」 2023-03-17 11:37
    关注

    参考GPT和自己的思路:

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

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

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

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

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

    评论

报告相同问题?

悬赏问题

  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。