学校信息系统:
假定学生与老师共用一套编号、姓名系统,作为基类Person。学生Student类专有数据排名,教师Teacher类专有数据科目(chinese、math、English)。
输入数据包含x、y、z、t。x为5位编号,y为姓名,z为专有数据,t为类别(学生为1,教师为2)。
输出数据为“Student:x y z”或者“Teacher:x y z”(无引号)。
#include<iostream>
using namespace std;
class Person{
protected:
double m_id;
string m_name;
public:
Person(double id,string name):m_id(id),m_name(name){
};
};
class Student:public Person{
private:
string p_data;
public:
Student(double id,string name,string data):Person(id,name),p_data(data){
};
void printstudent(){
cout<<"Student:"<<m_id<<' '<<m_name<<' '<<p_data<<endl;
};
};
class Teacher:public Person{
private:
string p_project;
public:
Teacher(double id,string name,string project):Person(id,name),p_project(project){
};
void printteacher(){
cout<<"Teacher:"<<m_id<<' '<<m_name<<' '<<p_project<<endl;
};
};
int main(){
int t;
double x;
string y,z;
cin>> x >> y >> z >> t;
Student s1(x,y,z);
Teacher t1(x,y,z);
if (t==1)
s1.printstudent();
else
t1.printteacher();
}
计算图形面积:
要求建立一个形状类Shape作为基类,圆类Circle和矩形类Rectangle继承于形状类Shape,并由此求出面积。具体要求如下:
(1)形状类Shape:包含图形参数x、y。对于圆,x和y均表示圆的半径(保证输入相等),而对于矩形,x表示矩形的长,y表示矩形的宽。同时包含初始化函数。
(2)圆类Circle:包含求面积函数。
(3)矩形类Rectangle:包含求面积函数。
本题中,Π取3.14。
输入包含三个数,x、y、t,x、y为图形参数(浮点型),t为图形类别(整数型),1表示圆形,2表示矩形。
输出为一个数,为图形面积,保留3位小数。
#include<iostream>
#include<iomanip>
const double PI=3.14;
using namespace std;
class Shape{
protected:
double x;
double y;
public:
Shape(double _x,double _y):x(_x),y(_y){
};
};
class Circle:public Shape{
public:
Circle(double r,double _r):Shape(r,_r){
};
void getarea(){
cout<<fixed<<setprecision(3)<<PI*x*y<<endl;
};
};
class Rectangle:public Shape{
public:
Rectangle(double l,double w):Shape(l,w){
};
void getarea(){
cout<<fixed<<setprecision(3)<<x*y<<endl;
};
};
int main(){
double x,y;
int t;
cin >> x >> y >> t;
Circle c(x,y);
Rectangle r(x,y);
if (t==1)
c.getarea();
else
r.getarea();
}
计算车重:
编写一个程序,其中有一个基础汽车类Vehicle,它具有一个需要传递参数的构造函数,类中的数据成员:车轮个数wheels和车重weight为保护属性;小车类Car私有继承于汽车类Vehicle,其中包含载人数passager_load;卡车类Truck私有继承于汽车类Vehicle,其中包含载人数passager_load和载重量payload。
输入数据包含a、b、c、d、t。a为车轮数,b为车重,c为载人数,d为载重量,t为类别(1为小车,2为卡车)。
输出格式为“wheels=x weight=y”(无引号,x、y为计算得数据,其中重量weight是总重,包含车重、人重和货物重,单个人重量记为65kg)
#include<iostream>
using namespace std;
class Vehicle{
protected:
double wheels;
double weight;
public:
Vehicle(double wl,double wh):wheels(wl),weight(wh){
}
};
class Car:private Vehicle{
private:
double passager_load;
public:
Car(double wl,double wh,double pl):Vehicle(wl,wh),passager_load(pl){
};
void car_load(){
cout<<"wheels="<<wheels<<" "<<"weight="<<weight+passager_load*65<<endl;;
}
};
class Truck:private Vehicle{
private:
double passager_load;
double payload;
public:
Truck(double wl,double wh,double pl,double pa):Vehicle(wl,wh),passager_load(pl),payload(pa){
};
void truck_load(){
cout<<"wheels="<<wheels<<" "<<"weight="<<weight+passager_load*65+payload<<endl;
}
};
int main(){
double a,b,c,d;
int t;
cin>>a>>b>>c>>d>>t;
if (t==1){
Car c1(a,b,c);
c1.car_load();
}
else{
Truck t1(a,b,c,d);
t1.truck_load();
}
}