第1个回答 2010-04-29
/*
1.声明Book与Ruler两个类,二者都有weight属性,定义二者的
一个友元函数totalWeight(),计算二者的重量和.
2。利用继承性与派生类来管理学生和教师档案.假设要管理下述几类人员的如下一些数据.
teacher(教师)类:姓名,性别,年龄,职称,担任课程;
student(学生)类:姓名,性别,年龄,学号,系别;
gradstudent(研究生)类:姓名,性别,年龄,学号,系别,导师。
要求每个类只设立构造函数以及显示类的对象数据的成员函数。
编写主函数,说明有关类对象,并对其类成员函数进行简单使用。
*/
#include <iostream>
#include <string>
using namespace std;
//因为Book中的友元函数要用到Ruler类,先声明但不定义
class Ruler;
class Book
{
public:
//构造函数
Book(double w = 10.0){weight = w;}
//友元函数
friend double totalWeight(class Book & b,class Ruler & r);
private:
double weight;
};
class Ruler
{
public:
Ruler(double w = 10.0){weight = w;}
//友元函数
friend double totalWeight(class Book & b,class Ruler & r);
private:
double weight;
};
double totalWeight(class Book & b,class Ruler & r)
{
//由于 totalWeight 是 Book 和 Ruler 类的友元函数
//因此可以直接引用它们的私有成员 weight
return b.weight + r.weight;
}
//student,teacher,gradstudent 类 的父类 Person 类
class Person
{
public:
//构造函数
Person(string n,string s,int a){name=n,sex=s,age=a;}
//显示类的对象数据的成员函数
void Display(){cout<<"name:"<<name<<endl<<"sex:"<<sex<<endl<<"age:"<<age<<endl;}
private:
string name;
string sex;
int age;
};
class Student: public Person
{
public:
Student(string n,string s,int a,string nu,string d):Person(n,s,a),number(nu),department(d){}
void Display(){Person::Display();cout<<"number:"<<number<<endl<<"department:"<<department<<endl<<endl;}
private:
string number;
string department;
};
class Teacher : public Person
{
public:
Teacher(string n,string s,int a,string t,string c):Person(n,s,a),title(t),course(c){}
void Display(){Person::Display();cout<<"title:"<<title<<endl<<"course"<<course<<endl<<endl;}
private:
string title;
string course;
};
class Gradstudent: public Person
{
public:
Gradstudent(string n,string s,int a,string nu,string d,string m):Person(n,s,a),number(nu),department(d),master(m){}
void Display(){Person::Display();cout<<"number:"<<number<<endl<<"department:"<<department<<endl<<"master:"<<master<<endl<<endl;}
private:
string number;
string department;
string master;
};
int main(int argc, char *argv[])
{
Book b;
Ruler r;
cout<<"the total weight of book and ruler is :"<<totalWeight(b,r)<<endl<<endl;
Student s("八戒","男",400,"003","高老庄");
Teacher t("唐僧","男",50,"长老","紧箍咒");
Gradstudent g("孙悟空","男",100,"001","花果山","唐僧");
s.Display();
t.Display();
g.Display();
return 0;
}本回答被提问者采纳