我们知道C++的一个主要目标是促进代码重用。公有继承是实现这种目标的机制之一,但并不是唯一。在继承中,继承类与基类是is-a的关系,但并不是所有的类都具有is-a的关系,有些类含有has-a的关系。这个情况下,我们将其中的一个类作为另一个类的成员,构成包含对象成员的类。
我们一student的类为例,student类可以包含学生名字与成绩。我们分别将学生名字与成绩用类来实现。名字可以用stirng类,成绩可以用valarray类实现。注意,使用公有继承时,类可以继承接口,可能还有实现。但对于包含类对象的类,不能自动获得被包含对象的接口,但其成员函数可以使用接口。
如图:
好了,看代码吧。对了,大家应该多家注意类成员的初始化
student.h
#ifndef STUENT_H_
#define STUDENT_H_
#include<iostream>
#include<string>
#include<valarray>
class Student
{
typedef std::valarray<double> ArrayDb;
std::string name;//类对象
ArrayDb 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;
friend std::ostream & operator <<(std::ostream & os,const Student &stu);
friend std::istream & operator >>(std::istream & os, Student &stu);
friend std::istream & getline(std::istream & os, Student & stu);
};
#endif // STUENT_H_
student.cpp
#include"student.h"
using namespace std;
const string & Student::Name() const
{
return name;
}
double & Student::operator[](int i)
{
return scores[i];
}
double Student::operator[](int i) const
{
return scores[i];
}
double Student::Average() const
{
if(scores.size()>0)
return scores.sum()/scores.size();
else
return 0;
}
ostream & Student::arr_out(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)
cout << endl;
}
if(i%5!=0)
os << endl;
}
else
os << "empty array ";
return os;
}
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;
stu.arr_out(os);
return os;
}
main.cpp
#include<iostream>
#include"student.h"
using namespace std;
void set1(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++)
set1(ada[i],quizzes);
cout << "\nresults:\n";
for(i=0;i<pupils;i++)
cout << ada[i].Name() << endl;
for(i=0;i<pupils;i++)
{
cout << endl <<ada[i];
cout << "average: " << ada[i].Average() << endl;
}
cout << "done.\n";
return 0;
}
void set1(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;
}
运行结果如下: