徐志摩的浪漫情诗:C++问题,要在11点20之前要答案~急

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/28 01:34:14
1.有一个关于学生的程序,程序中存在一些bugs,请将程序调试正确,使其输出为:
There are currently 0 students

A student has been added
Here are the grades for Student 1
100 75 89

A student has been added
Here are the grades for Student 2
83 92

A student has been added
Here are the grades for Student 3
62 91

There are currently 3 students

Student 2 has been deleted
Student 1 has been deleted
Student 3 has been deleted
程序代码为:
// Chapter 7 of C++ How to Program
// Debugging Problem (student.h)

#ifndef STUDENT_H
#define STUDENT_H

// class Student definition
class Student {

public:
Student( const char * );
~Student();
void displayGrades() const;
Student addGrade( int ) const;
static int getNumStudents();

private:
int *grades;
char *name;
int numGrades;
int idNum;

static int numStudents = 0;

}; // end class Student

#endif // STUDENT_H

// Chapter 7 of C++ How to Program
// Debugging Problem (student.cpp)

#include <iostream>

using std::cout;
using std::endl;

#include <iomanip>

using std::setw;

#include <cstring>

#include "student.h"

#include <new>
static int numStudents = 0;

// constructor
Student::Student( const char *nPtr )
{
grades = new int[ 1 ];
grades[ 0 ] = 0;
name = new char[ strlen( nPtr ) + 1 ];
strcpy( name, nPtr );
numGrades = 0;
numStudents++;

cout << "A student has been added\n";

} // end class Student constructor

// destructor
Student::~Student()
{
cout << name << " has been deleted\n";
delete grades;
delete name;
numStudents--;

} // end class Student destructor

// function displayGrades definition
void Student::displayGrades() const
{
cout << "Here are the grades for " << name << endl;

// output each grade
for ( int i = 0; i < numGrades; i++ )
cout << setw( 5 ) << grades[ i ];

cout << endl << endl;

} // end function displayGrades

// function addGrade definition
Student Student::addGrade( int grade ) const
{
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;

} // end function addGrade

// function getNumStudents definition
static int Student::getNumStudents()
{
return numStudents;

} // end function getNumStudents

下面还哟一半问题
// Chapter 7 of C++ How to Program
// Debugging Problem (debugging07.cpp)

#include <iostream>

using std::cout;
using std::endl;

#include "student.h"

int main()
{
cout << "There are currently " << Student:getNumStudents()
<< " students\n\n";

Student s1Ptr = new Student( "Student 1" );

s1Ptr->addGrade( 100 ).addGrade( 75 ).addGrade( 89 );
s1Ptr->displayGrades();

Student *s2Ptr = new Student( "Student 2" );
s2Ptr->addGrade( 83 )->addGrade( 92 );
s2Ptr->displayGrades();

const Student s3( "Student 3" );
s3.addGrade( 62 )->addGrade( 91 ).displayGrades();

cout << "There are currently " << getNumStudents()
<< " students\n\n";

delete [] s2Ptr;
delete s1Ptr;

return 0;

} // end main