(A)
#include<iostream>
using namespace std;
class Automobile //汽车类
{
protected:
int wheel; //保护数据成员车轮
double wieght; //保护数据成员车重
public:
Automobile(int wheel=0,double wieght=0) //构造函数
{
this->wheel=wheel;
this->wieght=wieght;
}
~Automobile() //析构函数
{
}
void show() //成员函数
{
cout<<"wheel:"<<wheel<<endl;
cout<<"wieght:"<<wieght<<endl;;
cout<<endl;
}
};
class car : private Automobile //小汽车类私有继承汽车类
{
protected:
int seat; //保护数据成员座位
public:
car(int seat=0) : Automobile(wheel,wieght) //构造函数
{
this->seat=seat;
}
~car() //析构函数
{
}
void show() //成员函数
{
cout<<"seat:"<<seat<<endl;
cout<<endl;
}
};
class StationWagon : private Automobile //客货两用车类,私有继承汽车类
{
protected:
int seat; //保护数据成员座位
double load; //保护数据成员载重
public:
StationWagon(int seat,double load) : Automobile(wheel,wieght) //构造函数
{
this->seat=seat;
this->load=load;
}
~StationWagon() //析构函数
{
}
void show() //成员函数
{
cout<<"seat:"<<seat<<endl;
cout<<"load:"<<load<<endl;
}
};
void main()
{
Automobile c1(4,10); //创建对象并初始化
Automobile *p;
p=&c1;
p->show();
car c2(30); //创建对象并初始化
car *p1;
p1=&c2;
p1->show();
StationWagon c3(50,100); //创建对象并初始化
StationWagon *p2;
p2=&c3;
p2->show();
}
(B)
#include<iostream>
#include<string> //字符串头文件
using namespace std;
class person
{
protected:
int number; //编号
bool sex; //性别
string name; //姓名
string address; //地址
public:
person(int number,bool sex,string name,string address) //构造函数
{
this->number=number;
this->sex=sex;
this->name=name;
this->address=address;
}
~person() //析构函数
{
}
void show() //成员函数
{
cout<<"编号:"<<number<<endl;
cout<<"姓名:"<<name<<endl;
cout<<"性别:"<<sex<<endl;
cout<<"住址:"<<address<<endl;
}
};
class teacher : public person //创建一教师类,公有继承人类
{
protected:
int grade; //级别
double salary; //月薪
public:
teacher(int grade,double salary) : person(number,sex,name,address) //构造函数
{
this->grade=grade;
this->salary=salary;
}
~teacher()
{
}
void show() //计算教师实际工资函数
{
double Factsalary; //创建一变量用来存放实际工资
Factsalary=grade*salary; //实际工资=级别*月薪
cout<<"该教师的实际工资为:"<<Factsalary<<endl;
}
};
class student : public person
{
protected:
int mark; //学分
int grade; //年级级别
public:
student(int mark,int grade) : person(number,sex,name,address) //构造函数
{
this->mark=mark;
this->grade=grade;
}
~student() //析构函数
{
}
void show() //计算总学分函数
{
int Nummark;
Nummark=mark+grade; //总学分=学分+年级级别
cout<<"该学生的总学分为:"<<Nummark<<endl;
}
};
void main()
{
person c1(54,0,"liunan","dkjflkdjf"); //创建函数对象并初始化
c1.show();
teacher c2(3,2000); //创建函数对象并初始化
c2.show();
student c3(10,3); //创建函数对象并初始化
c3.show();
}