将学生简化成姓名和一组考试分数后,可以使用一个包含两个成员的类来表示它:一个成员用于表示姓名,另一个成员用于表示分数。对于姓名,可以使用字符数组束表示,但这将限制姓名的长度。当然,也可以使用char指针和动态内存分配,然而正如第12章指出的,这将要求提供大量的支持代码。-种更
好的方法是,使用一个由他人开发好的类的对象来表示。例如,可以使用一个String类(参见第12章)或
标准C++的string 类的对象来表示姓名。较简单的选择是使用string 类,因为C++库提供了这个类的所有
#ifndef STUDENTC_H_ #define STUDENTC_H_ #includestudent.cpp#include #include class Student { private: typedef std::valarray ArrayDb; std::string name; ArrayDb scores; //私有方法,将scores输出 std::ostream & arr_out(std::ostream & os) const; public: Student() : name("Null Student"), scores() {} explicit Student(const std::string & s) : name(s), scores() {} explicit Student(int n) : name("Nully"), scores(n) {} Student(const std::string & s, int n) : name(s), scores(n) {} Student(const std::string & s, const ArrayDb & a) : name(s), scores(a) {} Student(const char * str, const double * pd, int n) : name(str), scores(pd, n) {} ~Student() {} double Average() const; const std::string & Name() const; double & operator[](int i); double operator[](int i) const; //友元 //input friend std::istream & operator>>(std::istream & is, Student & stu); friend std::istream & getline(std::istream & is, Student & stu); //output friend std::ostream & operator<<(std::ostream & os, const Student & stu); }; #endif // !STUDENTC_H_
#include "studentc.h"
using std::ostream;
using std::endl;
using std::istream;
using std::string;
//private
ostream & Student::arr_out(std::ostream & os) const
{
int i;
int lim = scores.size();
if (lim > 0)
{
for (i = 0; i < lim; i++)
{
os << scores[i] << " ";
if (i % 5 == 4)
os << endl;
}
if (i % 5 != 0)
os << endl;
}
else
os << " empty array ";
return os;
}
//public
double Student::Average() const
{
if (scores.size() > 0)
return scores.sum();
else
return 0;
}
const std::string & Student::Name() const
{
return name;
}
double & Student::operator[](int i)
{
return scores[i];
}
double Student::operator[](int i) const
{
return scores[i];
}
//friends
istream & operator>>(istream & is, Student & stu)
{
is >> stu.name;
return is;
}
istream & getline(istream & is, Student & stu)
{
getline(is, stu.name);
return is;
}
ostream & operator<<(ostream & os, const Student & stu)
{
os << "Scores for " << stu.name << ":n";
stu.arr_out(os);
return os;
}
main.cpp
#include#include "studentc.h" using std::cin; using std::cout; using std::endl; void set(Student & sa, int n); const int pupils = 3; const int quizzes = 5; int main() { Student ada[pupils] = { Student(quizzes), Student(quizzes), Student(quizzes) }; int i; for (i = 0; i < pupils; ++i) set(ada[i], quizzes); cout << "nStudent List:n"; for (i = 0; i < pupils; ++i) cout << ada[i].Name() << endl; cout << "nResults:"; for (i = 0; i < pupils; ++i) { cout << endl << ada[i]; cout << "average: " << ada[i].Average() << endl; } cout << "Done.n"; return 0; } void set(Student & sa, int n) { cout << "Please enter the student's name: "; getline(cin, sa); cout << "Please enter " << n << " quiz scores:n"; for (int i = 0; i < n; i++) cin >> sa[i]; while (cin.get() != 'n') continue; }



