实验10 多继承

1-在职研究生

#include<iostream>
using namespace std;
#include<cstring>
class CPeople
{
protected:
	string name;
	char sex;
	int age;
public:
	CPeople(){}
	CPeople(string na,char s,int a ):name(na), sex(s), age(a) {}
	void print(){
		cout << "People:" << endl;
		cout << "Name: " << name << endl;
		cout << "Sex: " << sex << endl;
		cout << "Age: " << age << endl;
		cout << endl;
	}
};
class CStudent :virtual public CPeople
{
protected:
	string number;
	float score;
public:
	CStudent(){}
	CStudent(float sco, string num, string na, char s, int a) {
		score = sco;
		number = num;
		name = na;
		sex = s;
		age = a;
	}
	void print() {
		cout << "Student:" << endl;
		cout << "Name: " << name <<endl;
		cout << "Sex: " << sex << endl;
		cout << "Age: " << age << endl;
		cout << "No.: " << number << endl;
		cout << "Score: " << score << endl;
		cout << endl;
	}
};
class CTeacher : virtual public CPeople
{
protected:
	string position;
	string Department;
public:
	CTeacher(){}
	CTeacher(string na, char s, int a, string po, string De) {
		name = na;
		sex = s;
		age = a;
		position = po;
		Department = De;
	}
	void print(){
		cout << "Teacher:" << endl;
		cout << "Name: " << name << endl;
		cout << "Sex: " << sex << endl;
		cout << "Age: " << age << endl;
		cout << "Position: " << position << endl;
		cout << "Department " << Department << endl;
		cout << endl;
	}
};
class CGradOnWork :public CTeacher,public CStudent
{
	string Direction;
	string Tutor;
public:
	CGradOnWork(){}
	CGradOnWork(string na, char s, int a, string po, string De, float sco, string num, string Di,string Tu) {
		name = na;
		sex = s;
		age = a;
		position = po;
		Department = De;
		score = sco;
		number = num;
		Direction = Di;
		Tutor = Tu;
	}
	void print() {
		cout << "GradOnWork:" << endl;
		cout << "Name: " << name << endl;
		cout << "Sex: " << sex << endl;
		cout << "Age: " << age << endl;
		cout << "No.: " << number << endl;
		cout << "Score: " << score << endl;
		cout << "Position: " << position << endl;
		cout << "Department: " << Department << endl;
		cout << "Direction: " << Direction << endl;
		cout << "Tutor: " << Tutor << endl;
		cout << endl;
	}
};
int main() {
	string name;
	char sex;
	int age;
	string number;
	float score;
	string position;
	string Department;
	string Direction;
	string Tutor;
	cin >> name >> sex >> age >> number >> score >> position >> Department >> Direction >> Tutor;
	CPeople CP(name, sex, age);
	CP.print();
	CStudent CS(score, number, name, sex, age);
	CS.print();
	CTeacher CT(name, sex, age, position, Department);
	CT.print();
	CGradOnWork CG(name, sex, age, position, Department, score, number, Direction, Tutor);
	CG.print();
}

2-交通工具

#include<iostream>
using namespace std;
#include<cstring>
class CVehicle
{
protected:
	int max_speed;
	int speed;
	int weight;
public:
	CVehicle(){}
	CVehicle(int mas,int sp,int wei):max_speed(mas),speed(sp),weight(wei) {}
	void display() {
		cout << "Vehicle:" << endl;
		cout << "max_speed:" << max_speed << endl;
		cout << "speed:" << speed << endl;
		cout<<"weight:" << weight << endl;
		cout << endl;
	}
};
class CBicycle :virtual public CVehicle
{
protected:
	int height;
public:
	CBicycle(){}
	CBicycle(int mas, int sp, int wei,int hei){
		max_speed = mas;
		speed = sp;
		weight = wei;
		height = hei;
	}
	void display() {
		cout << "Bicycle:" << endl;
		cout << "max_speed:" << max_speed << endl;
		cout << "speed:" << speed << endl;
		cout << "weight:" << weight << endl;
		cout << "height:" << height << endl;
		cout << endl;
	}
};
class CMotocar :virtual public CVehicle
{
protected:
	int seat_num;
public:
	CMotocar(){}
	CMotocar(int mas, int sp, int wei,int seat) {
		max_speed = mas;
		speed = sp;
		weight = wei;
		seat_num = seat;
	}
	void display() {
		cout << "Motocar:" << endl;
		cout << "max_speed:" << max_speed << endl;
		cout << "speed:" << speed << endl;
		cout << "weight:" << weight << endl;
		cout << "seat_num:" << seat_num << endl;
		cout << endl;
	}
};
class CMotocycle :public CBicycle, public CMotocar
{
public:
	CMotocycle(){}
	CMotocycle(int mas, int sp, int wei, int hei, int seat) {
		max_speed = mas;
		speed = sp;
		weight = wei;
		height = hei;
		seat_num = seat;
	}
	void display() {
		cout << "Motocycle:" << endl;
		cout << "max_speed:" << max_speed << endl;
		cout << "speed:" << speed << endl;
		cout << "weight:" << weight << endl;
		cout << "height:" << height << endl;
		cout << "seat_num:" << seat_num << endl;
		cout << endl;
	}
};
int main() {
	int max_speed, speed, weight, height, seat_num;
	cin >> max_speed >> speed >> weight >> height >> seat_num;
	CVehicle CV(max_speed, speed, weight);
	CV.display();
	CBicycle CB(max_speed, speed, weight, height);
	CB.display();
	CMotocar CM(max_speed, speed, weight, seat_num);
	CM.display();
	CMotocycle CMo(max_speed, speed, weight, height, seat_num);
	CMo.display();
}

3-商旅信用卡

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
class VIP
{
public:
    VIP(int number1, int score1)
    {
        number = number1;
        score = score1;
    }
    int add(float m)
    {
        score += m;
        return score;
    }
protected:
    int number;
    static int  score; 
};

int VIP::score = 0;

class Creditcard 
{
public:
    Creditcard(int number1, string name1, int sum1, float pay1, int score1)
    {
        number3 = number1;
        name = name1;
        sum = sum1;
        pay = pay1;
        score3 = score1;
    }
    void use(float m) 
    {
        if (m + pay > sum)
        {
        }
        else
        {
            pay += m;
            score3 = score3 + m;
        }
    }
    void showpay()
    {
        cout << pay << endl;
    }
    void back(float m)
    {
        pay -= m;
        score3 = score3 - m;
    }
    int add(float m)
    {
        score3 = score3 + m;
        return score3;
    }
protected:
    int number3;
    string name;
    int sum;
    float pay;
    static float score3; 
};

float Creditcard::score3 = 0;

class Tripcreditcard :public VIP, public Creditcard
{
public:
    Tripcreditcard(int number1, int number2, string name1, int sum1, float pay1, int score1, int score2) :Creditcard(number2, name1, sum1, pay1, score2), VIP(number1, score1)
    {

    }
    void add(float m)
    {
        int s1, s2, s3;
        s1 = VIP::add(m);
        s2 = Creditcard::add(m);
        pay += m;
    }
    void change(float m)
    {
        int s1, s2, s3;
        s2 = m / 2;
        score = score + s2;
        score3 = score3 - m;
    }
    void display()
    {
        cout << number << " ";
        cout << score << endl;
        cout << number3 << " " << name << " " << pay << " " << int(score3) << endl;
    }

};

int main()
{
    int number1, number2;
    string name1;
    float m;
    int sum1;
    int t, i;
    char a;
    cin >> number1 >> number2 >> name1 >> sum1;
    Tripcreditcard Tripcreditcard1(number1, number2, name1, sum1, 0, 0, 0);
    cin >> t;
    for (i = 0; i < t; i++)
    {
        cin >> a >> m;
        if (a == 'o')
        {
            Tripcreditcard1.add(m);
        }
        else if (a == 'c')
        {
            Tripcreditcard1.use(m);
        }
        else if (a == 'q')
        {
            Tripcreditcard1.back(m);
        }
        else if (a == 't')
        {
            Tripcreditcard1.change(m);
        }
    }
    Tripcreditcard1.display();
    return 0;
}

4-日程安排

#include<iostream>
using namespace std;
#include<cstring>
#include <iomanip>
class Date
{
protected:
	int day;
	int year;
	int month;
public:
	Date() {}
	Date(int d, int y, int m) :year(y), month(m), day(d) {}
};
class Time
{
protected:
	int hour;
	int minute;
	int second;
public:
	Time() {}
	Time(int h, int min, int s) :hour(h), minute(min), second(s) {}
};
class Schedule :virtual public Date, virtual public Time
{
protected:
	int ID;
public:
	int ToDate() {
		return year * 100000 + month * 10000 + 1000 * day;
	}
	int ToTime() {
		return hour * 100 + minute * 10 + second;
	}
	Schedule() {}
	Schedule(int d, int y, int m, int h, int min, int s, int i) :Date(d, y, m), Time(h, min, s), ID(i) {}
	friend bool before(const Schedule& s1, const Schedule& s2) {
	};
	void show() {
		cout << ID << ": " << year << setfill('0') << setw(2) << month << "/" << setw(2) << day << " "
			<< setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second << endl;
	}
};
bool before(const Schedule& s1, const Schedule& s2) {
	if (s1.ToData() != s2.ToData()) {
		return ToData() < s2.ToData();
	}
	else {
		return ToTime() < s2.ToTime();
	}
}
int  main() {
	int day;
	int year;
	int month;
	int hour;
	int minute;
	int second;
	int ID;
	int n;
	Schedule s1(99, 9999, 99, 99, 99, 99, 99);
	while (cin >> n, n != 0) {
		cin >> ID >> year >> month >> day >> hour >> minute >> second;
		Schedule s2(day, year, month, hour, minute, second, ID);
		if (before(s1, s2)) {
			s1 = s2;
		}
	}
	cout << "The urgent schedule is No.";

}

5-计算宝宝账号收益

#include<iostream>
using namespace std;
#include<cstring>
class CPeople
{
protected:
	char id[20];
	char name[10];
public:
	CPeople() {}
	CPeople(char i[20], char n[10]) {
		strcpy(id, i);
		strcpy(name, n);
	}
};
class CInternetUser : public CPeople
{
protected:
	char password[20];
public:
	void registerUser(char i[20], char n[10], char pass[20]) {
		strcpy(id, i);
		strcpy(name, n);
		strcpy(password, pass);
	}
};
class CBankCustomer : public CPeople
{
protected:
	double balance;
public:
	CBankCustomer() { balance = 0; }
	void openAccount(char na[10], char i[20]) {
		strcpy(name, na);
		strcpy(id, i);
	}
	void deposit(double money) {
		balance += money;
	}
	bool withdraw(double money) {
		if (balance - money >= 0) {
			balance -= money;
			return 1;
		}
		else
			return 0;
	}
};
class CInternetBankCustomer :public CBankCustomer, public CInternetUser
{
protected:
	double Int_balance;
	double yesterday_balance;
	double today_earnings;
	double today_interest;
	double yesterday_interest;
public:
	CInternetBankCustomer() {
		Int_balance = 0.00;
		yesterday_balance = 0.00;
		yesterday_interest = 0.00;
		today_earnings = 0.00;
		today_interest = 0.00;
	}
	bool deposit(double money) {
		if (balance < money)
			return 0;
		else {
			balance -= money;
			Int_balance += money;
			return 1;
		}
	}
	bool withdraw(double money) {
		if (Int_balance - money >= 0) {
			Int_balance -= money;
			balance += money;
			return 1;
		}
		else
			return 0;
	}
	void setInterest(double Interest) {
		yesterday_interest = today_interest;
		today_interest = Interest;
	}
	void calculateProfit() {
		today_earnings = yesterday_balance * 0.0001 * yesterday_interest;
		Int_balance += today_earnings;
		yesterday_balance = Int_balance;
	}
	void print() {
		cout << "Name: " << CBankCustomer::name << " ID: " << CBankCustomer::id << endl;
		cout << "Bank balance: " << balance << endl;
		cout << "Internet bank balance: " << Int_balance << endl;
	}
	bool login(char i[20], char pass[20]) {
		return  (!strcmp(CInternetUser::id, i) && !strcmp(password, pass));
	}
};
int main()
{
	int t, no_of_days, i;
	char i_xm[20], i_id[20], i_mm[20], b_xm[20], b_id[20], ib_id[20], ib_mm[20];
	double money, interest;
	char op_code;
	cin >> t;
	while (t--)
	{
		//输入互联网用户注册时的用户名,id,登陆密码
		cin >> i_xm >> i_id >> i_mm;
		//输入银行开户用户名,id
		cin >> b_xm >> b_id;
		//输入互联网用户登陆时的id,登陆密码
		cin >> ib_id >> ib_mm;
		CInternetBankCustomer ib_user;
		ib_user.registerUser(i_xm, i_id, i_mm);
		ib_user.openAccount(b_xm, b_id);
		if (ib_user.login(ib_id, ib_mm) == 0)  //互联网用户登陆,若id与密码不符;以及银行开户姓名和id与互联网开户姓名和id不同
		{
			cout << "Password or ID incorrect" << endl;
			continue;
		}
		//输入天数
		cin >> no_of_days;
		for (i = 0; i < no_of_days; i++)
		{
			//输入操作代码, 金额, 当日万元收益
			cin >> op_code >> money >> interest;
			switch (op_code)
			{
			case 'S':  //从银行向互联网金融帐户存入
			case 's':
				if (ib_user.deposit(money) == 0)
				{
					cout << "Bank balance not enough" << endl;
					continue;
				}
				break;
			case 'T':  //从互联网金融转入银行帐户
			case 't':
				if (ib_user.withdraw(money) == 0)
				{
					cout << "Internet bank balance not enough" << endl;
					continue;
				}
				break;
			case 'D':  //直接向银行帐户存款
			case 'd':
				ib_user.CBankCustomer::deposit(money);
				break;
			case 'W':  //直接从银行帐户取款
			case 'w':
				if (ib_user.CBankCustomer::withdraw(money) == 0)
				{
					cout << "Bank balance not enough" << endl;
					continue;
				}
				break;
			default:
				cout << "Illegal input" << endl;
				continue;
			}
			ib_user.setInterest(interest);
			ib_user.calculateProfit();
			//输出用户名,id
			//输出银行余额
			//输出互联网金融账户余额
			ib_user.print();
		}
	}
}
//老师的代码
#include<iostream>
using namespace std;

class CPeople
{
protected:
    int age;
    string name, sex;
public:
    CPeople(string n, string s, int a): name(n), sex(s), age(a) {}
    void print()
    {
        cout<<"People:"<<endl
            <<"Name: "<<name<<endl
            <<"Sex: "<<sex<<endl
            <<"Age: "<<age<<endl<<endl;
    }
};

class CStu: virtual public CPeople
{
protected:
    double grade;
    string id;
public:
    CStu(string n, string s, int a, string i, double g): CPeople(n, s, a), id(i), grade(g) {}
    void print()
    {
        cout<<"Student:"<<endl
            <<"Name: "<<name<<endl
            <<"Sex: "<<sex<<endl
            <<"Age: "<<age<<endl
            <<"No.: "<<id<<endl
            <<"Score: "<<grade<<endl<<endl;
    }
};

class CTutor: virtual public CPeople
{
protected:
    string pos, dept;
public:
    CTutor(string n, string s, int a, string p, string d): CPeople(n, s, a), pos(p), dept(d) {}
    void print()
    {
        cout<<"Teacher:"<<endl
            <<"Name: "<<name<<endl
            <<"Sex: "<<sex<<endl
            <<"Age: "<<age<<endl
            <<"Position: "<<pos<<endl
            <<"Department: "<<dept<<endl<<endl;
    }
};

class CGradOnWork: public CStu, public CTutor
{
    string dir, Tut;
public:
    CGradOnWork(string n, string s, int a, string i, double g, string p, string d, string di, string t):
      CPeople(n, s, a), CStu(n, s, a, i, g), CTutor(n, s, a, p, d), dir(di), Tut(t) {}
    void print()
    {
        cout<<"GradOnWork:"<<endl
            <<"Name: "<<name<<endl
            <<"Sex: "<<sex<<endl
            <<"Age: "<<age<<endl
            <<"No.: "<<id<<endl
            <<"Score: "<<grade<<endl
            <<"Position: "<<pos<<endl
            <<"Department: "<<dept<<endl
            <<"Direction: "<<dir<<endl
            <<"Tutor: "<<Tut<<endl<<endl;
    }
};

int main()
{   
    int a;
    double g;
    string n, s, i, p, d, di, t;

    cin>>n>>s>>a>>i>>g>>p>>d>>di>>t;
  
    CGradOnWork pp(n, s, a, i, g, p, d, di, t);
    pp.CPeople::print();
    pp.CStu::print();
    pp.CTutor::print();
    pp.print();

    return 0;
}

//
main还可以写成:
int main()
{
    int a;
    double g;
    string n, s, i, p, d, di, t;

    cin>>n>>s>>a>>i>>g>>p>>d>>di>>t;
    CGradOnWork* pp=new CGradOnWork(n, s, a, i, g, p, d, di, t);
    ((CPeople*)pp)->print();
    ((CStu*)pp)->print();
    ((CTutor*)pp)->print();
    pp->print();

    return 0;
}

======================================================================================
#include <iostream>
using namespace std;

class CVehicle{
protected:
    int maxSpeed, speed, weight;
public:
    CVehicle(int m, int s, int w): maxSpeed(m), speed(s), weight(w) {}
    void print()
    {
        cout<<"Vehicle:"<<endl
            <<"max_speed:"<<maxSpeed<<endl
            <<"speed:"<<speed<<endl
            <<"weight:"<<weight<<endl<<endl;
    }
};

class CBicycle: virtual public CVehicle{
protected:
    int height;
public:
    CBicycle(int n, int s, int w, int h): CVehicle(n, s, w), height(h) {}
    void print()
    {
        cout<<"Bicycle:"<<endl
            <<"max_speed:"<<maxSpeed<<endl
            <<"speed:"<<speed<<endl
            <<"weight:"<<weight<<endl
            <<"height:"<<height<<endl<<endl;
    }
};

class CMotorCar: virtual public CVehicle
{
protected:
    int seat;
public:
    CMotorCar(int n, int s, int w, int st): CVehicle(n, s, w), seat(st) {}
    void print()
    {
        cout<<"Motocar:"<<endl
            <<"max_speed:"<<maxSpeed<<endl
            <<"speed:"<<speed<<endl
            <<"weight:"<<weight<<endl
            <<"seat_num:"<<seat<<endl<<endl;
    }
};

class CMotorCycle: public CBicycle, public CMotorCar
{
public:
    CMotorCycle(int n, int s, int w, int h, int st):
      CVehicle(n, s, w), CBicycle(n, s, w, h), CMotorCar(n, s, w, st) {}
    void print()
    {
        cout<<"Motocycle:"<<endl
            <<"max_speed:"<<maxSpeed<<endl
            <<"speed:"<<speed<<endl
            <<"weight:"<<weight<<endl
            <<"height:"<<height<<endl
            <<"seat_num:"<<seat<<endl<<endl;
    }
};

int main()
{
    int n, s, w, h, st;
    cin>>n>>s>>w>>h>>st;

    CMotorCycle v(n, s, w, h, st);
    v.CVehicle::print();
    v.CBicycle::print();
    v.CMotorCar::print();
    v.print();

    return 0;
}

///
main方法还可以写成:

int main()
{
    int n, s, w, h, st;
    cin>>n>>s>>w>>h>>st;

    CMotorCycle* p=new CMotorCycle(n,s,w,h,st);
    ((CVehicle*)p)->print();
    ((CBicycle*)p)->print();
    ((CMotorCar*)p)->print();
    p->print();

    return 0;
}



======================================================================================
#include<iostream>
using namespace std;

class Journeycard{
protected:
    int cardno,score;
public:
    Journeycard(int no):cardno(no){score=0;}
    void order(float m){  //积分
        score+=(int)m;
    }
};

class Credit_Card{
protected:
    int cardno,limit,score;
    float money;
    string name;
public:
    Credit_Card(int no,int limi,string name1):cardno(no),limit(limi),name(name1){
       score=0;money=0;
    }
    int consume(float m){  //信用卡消费
        if((int)(m+money)<limit)
        {
            money+=m;
            score+=(int)m;
            return 1;
        }
        else
            return 0;
    }
    void refund(float m){ //信用卡退款
        money-=m;
        score-=(int)m;
    }
};

class CJCcard:public Journeycard,public Credit_Card{
public:
    CJCcard(int no1,int no2,string na,int limi):Journeycard(no1),Credit_Card(no2,limi,na){}
    void order2(float m){  //旅程网下订单
        if(consume(m))
           order(m);
    }
    void exchange(int m){  //积分兑换
        Credit_Card::score-=(int)m;
        Journeycard::score+=(int)m/2;
    }
    void print(){
        cout<<Journeycard::cardno<<" "<<Journeycard::score<<endl;
        cout<<Credit_Card::cardno<<" "<<Credit_Card::name<<" "<<Credit_Card::money<<" "<<Credit_Card::score<<endl;
    }
};

int main()
{
    int no1,no2,limit;
    string name;

    cin>>no1>>no2>>name>>limit;
    CJCcard c1(no1,no2,name,limit);

    int n;
    char ch;
    float mon;

    cin>>n;
    while(n--)
    {
        cin>>ch>>mon;
        switch(ch){
        case 'o':c1.order2(mon);break;
        case 'c':c1.consume(mon);break;
        case 'q':c1.refund(mon);break;
        case 't':c1.exchange(int(mon));break;
        }
    }
    c1.print();

    return 0;
}

======================================================================================
注意:两个对象s1和s2比较大小,返回值若为true,则s1在s2的前面。
函数参数的声明可以有两种方式:
1、bool before(const Schedule&s1, const Schedule& s2) 
2、bool before(Schedule s1, Schedule s2) 

一、使用自定义对象数组
#include<iostream>
#include <iomanip>
#include <algorithm>
using namespace std;

class CDate {
    protected:
        int y, mon, d;
};

class CTime{
    protected:
        int h, m, s;
};

class Schedule:public CTime,public CDate{
        int ID;
    public:
        Schedule() {}
        void set(int i,int x1,int y1,int z1,int a1,int b1,int c1){
            y=x1;
            mon=y1;
            d=z1;
            h=a1;
            m=b1;
            s=c1;
            ID=i;
        }
        friend bool before(const Schedule&s1, const Schedule& s2);
        void display() {
            cout << "No." << ID << ": " << y << "/"<<setfill('0')
            <<setw(2)<< mon << "/"<<setw(2)<< d << " "
            << setw(2) << h << ":"<<setw(2)<< m << ":"<<setw(2)<< s << endl;
        }
};

bool before(const Schedule&s1, const Schedule& s2) {
    if(s1.y > s2.y)
        return false;
    if(s1.mon>s2.mon)
        return false;
    if(s1.d>s2.d)
        return false;
    if(s1.h>s2.h)
        return false;
    if(s1.m>s2.m)
        return false;
    if(s1.s>=s2.s)
        return false;

    return true;
}

int main() {
    int x, y, z,a,b,c;
    int t;
    int count=0;  //用于记录数组元素个数
    Schedule s[20];

    cin >> t;
    while (t != 0) {
       cin >> x >> y >> z;
       cin >> a >> b >> c;
       s[count++].set(t, x, y, z, a, b, c);
       cin >> t;
     }
     sort(s, s+count,before);
     cout << "The urgent schedule is ";
     s[0].display();

     return 0;
}

//
二、使用vector动态数组,放多个对象
#include<iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
using namespace std;

class CDate {
    protected:
        int y, mon, d;
    public:
        CDate() {}
        CDate(int a, int b, int c) :y(a), mon(b), d(c) {}
};

class CTime{
    protected:
        int h, m, s;
    public:
        CTime() {}
        CTime(int a,int b,int c):h(a),m(b),s(c) { }
};

class Schedule:public CTime,public CDate{
    protected:
        int ID;
    public:
        Schedule() {}
        Schedule(int i,int x,int y,int z,int a,int b,int c):CDate(x,y,z),CTime(a,b,c),ID(i) {}
        friend bool before(const Schedule&s1, const Schedule& s2);
        void display() {
            cout << "No." << ID << ": " << y << "/"<<setfill('0')
            <<setw(2)<< mon << "/"<<setw(2)<< d << " "
            << setw(2) << h << ":"<<setw(2)<< m << ":"<<setw(2)<< s << endl;
        }
};

bool before(const Schedule&s1, const Schedule& s2) {
    if(s1.y > s2.y)
        return false;
    if(s1.mon>s2.mon)
        return false;
    if(s1.d>s2.d)
        return false;
    if(s1.h>s2.h)
        return false;
    if(s1.m>s2.m)
        return false;
    if(s1.s>=s2.s)
        return false;
    return true;
}

int main() {
    int x, y, z,a,b,c;
    int t;
    cin >> t;
    vector<Schedule> objarr;
    while (t != 0) {
       cin >> x >> y >> z;
       cin >> a >> b >> c;
       Schedule obj(t, x, y, z, a, b, c);
       objarr.push_back(obj);
       cin >> t;
     }
     sort(objarr.begin(), objarr.end(),before);
     cout << "The urgent schedule is ";
     objarr[0].display();
     return 0;
}
======================================================================================
一、第一种
#include <iostream>
using namespace std;

class CPeople {
   protected:
      string name,id; //  姓名、身份号码
   public:
    CPeople(string name,string id):name(name),id(id){}
};

class CInternetUser:public CPeople {   //网络用户
    protected:
        string password;  //密码
    public:
        CInternetUser(string name,string id,string password):CPeople(name,id),password(password){}
        /*void registerUser(string n, string i, string p){  //注册,有构造函数,可缺省
            name=n;
            id=i;
            password=p;
        }*/    
        int login(string i, string p){  //登录
            if (id!=i || password!=p)
                return 0;
            return 1;
         }
};

class CBankCustomer:public CPeople {  //银行用户
    protected:
        double balance; //余额
    public:
        CBankCustomer(string name,string id):CPeople(name,id),balance(0){}

       /* void openAccount(string n, string i){  //开户,有构造函数,可缺省
            balance = 0;
            name=n;
            id=i;
         }*/

         int deposit(double m){  //存款
             balance += m;
             return 1;
         }
         int withdraw(double m){  //取款
             if (m > balance)
                return 0;
             balance -= m;
             return 1;
          }
};

class CInternetBankCustomer:public CInternetUser,public CBankCustomer {  //网络银行账户
    double tdbal, ldbal, profit, tdint, ldint;   //余额, 前一日余额, 当日收益,今日万元收益和上一日万元收益
public:
    CInternetBankCustomer(string name1,string id1,string password,string name,string id):CInternetUser(name1,id1,password),CBankCustomer(name,id){}
    int login(string  i, string p){  //网络银行账户登陆
        if(CInternetUser::id!=CBankCustomer::id || CInternetUser::id!=i || password!=p)
               return 0;
        tdbal = ldbal = profit = tdint = ldint = 0;
        return 1;
    }
    void setInterest(double i){  //今日万元收益
        tdint = i / 10000;
    }
    int deposit(double m){  //网络银行账户存款:从银行向互联网账户存款
        if (m > balance)
              return 0;
        balance -= m;
        tdbal += m;
        return 1;
     }
     int withdraw(double m){  //网络银行账户取款:从互联网账户转向银行账户
         if (m > tdbal)
            return 0;
         balance += m;
         tdbal -= m;
         return 1;
      }
      void calculateProfit(){  //算利润
          profit = ldbal * ldint;   //利润=上一日余额*上一日万元收益
          tdbal += profit;          //利润计入余额
      }
      void print(){
          cout << "Name: " << CBankCustomer::name << " ID: " << CBankCustomer::id << endl
               << "Bank balance: " << balance << endl
               << "Internet bank balance: " << tdbal << endl;
          ldbal = tdbal;ldint = tdint;  //注意:每过一天,上一日余额和上一日万元收益要更新为当天的
       }
};
int main() {
    int t, no_of_days, i;
    string i_xm, i_id, i_mm, b_xm, b_id, ib_id, ib_mm;
    double money, interest;char op_code;//输入测试案例数t
    cin >> t;
    while (t--){//输入互联网用户注册时的用户名,id,登陆密码
       cin >> i_xm >> i_id >> i_mm;//输入银行开户用户名,id
       cin >> b_xm >> b_id;//输入互联网用户登陆时的id,登陆密码
       cin >> ib_id >> ib_mm;
       CInternetBankCustomer ib_user(i_xm, i_id, i_mm,b_xm, b_id);
       if (!ib_user.login(ib_id, ib_mm)) //互联网用户登陆,若id与密码不符;以及银行开户姓名和id与互联网开户姓名和id不同
        { cout << "Password or ID incorrect" << endl;
          continue;
        }//输入天数
        cin >> no_of_days;
        for (i=0; i < no_of_days; i++){//输入操作代码, 金额, 当日万元收益
          cin >> op_code >> money >> interest;
          switch (op_code){
              case 'S': //从银行向互联网金融帐户存入
              case 's': if (!ib_user.deposit(money)){
                            cout << "Bank balance not enough" << endl;
                            continue;
                         }
                         break;
               case 'T': //从互联网金融转入银行帐户
               case 't':if (!ib_user.withdraw(money)){
                            cout << "Internet bank balance not enough" << endl;
                            continue;
                         }
                         break;
               case 'D': //直接向银行帐户存款
               case 'd':ib_user.CBankCustomer::deposit(money);
                        break;
               case 'W': //直接从银行帐户取款
               case 'w':if (!ib_user.CBankCustomer::withdraw(money)){
                            cout << "Bank balance not enough" << endl;
                            continue;
                        }
                        break;
               default:cout << "Illegal input" << endl;
                       continue;
           }
           ib_user.setInterest(interest); //设置利润
           ib_user.calculateProfit();//算利润
           ib_user.print();//输出用户名,id//输出银行余额 //输出互联网金融账户余额
           cout << endl;
        }
    }
    return 0;
}


二、第二种写法:使用注册、开户操作,构造函数缺省了

#include <iostream>
using namespace std;

class CPeople {
   protected:
      string id, name;
};

class CInternetUser:public CPeople {
    protected:
        string password;
    public:
        void registerUser(string n, string i, string p){  //注册
            name=n;
            id=i;
            password=p;
        }
        int login(string i, string p){
            if (id!=i || password!=p)
                return 0;
            return 1;
         }
};

class CBankCustomer:public CPeople {
    protected:
        double balance;
    public:
        void openAccount(string n, string i){  //开户
            balance = 0;
            name=n;
            id=i;
         }
         int deposit(double m){
             balance += m;
             return 1;
         }
         int withdraw(double m){
             if (m > balance)
                return 0;
             balance -= m;
             return 1;
          }
};

class CInternetBankCustomer:public CInternetUser,public CBankCustomer {
    double tdbal, ldbal, profit, tdint, ldint;//today balance,lastday interest
public:
    int login(string  i, string p){
        if(CInternetUser::id!=CBankCustomer::id || CInternetUser::id!=i || password!=p)
            return 0;
        tdbal = ldbal = profit = tdint = ldint = 0;
        return 1;
    }
    void setInterest(double i){
        tdint = i / 10000;
    }
    int deposit(double m){
        if (m > balance)
            return 0;
        balance -= m;
        tdbal += m;
        return 1;
     }
     int withdraw(double m){
         if (m > tdbal)
            return 0;
         balance += m;
         tdbal -= m;
         return 1;
      }
      void calculateProfit(){
          profit = ldbal * ldint;
          tdbal += profit;
      }
      void print(){
          cout << "Name: " << CBankCustomer::name << " ID: " << CBankCustomer::id << endl
               << "Bank balance: " << balance << endl
               << "Internet bank balance: " << tdbal << endl;
          ldbal = tdbal;ldint = tdint;
       }
};
int main() {
    int t, no_of_days, i;
    string i_xm, i_id, i_mm, b_xm, b_id, ib_id, ib_mm;
    double money, interest;char op_code;//输入测试案例数t
    cin >> t;
    while (t--){//输入互联网用户注册时的用户名,id,登陆密码
       cin >> i_xm >> i_id >> i_mm;//输入银行开户用户名,id
       cin >> b_xm >> b_id;//输入互联网用户登陆时的id,登陆密码
       cin >> ib_id >> ib_mm;

       CInternetBankCustomer ib_user;
       ib_user.registerUser(i_xm, i_id, i_mm); //调用注册函数赋值
       ib_user.openAccount(b_xm, b_id); //调用开户函数赋值

       if (!ib_user.login(ib_id, ib_mm)) //互联网用户登陆,若id与密码不符;以及银行开户姓名和id与互联网开户姓名和id不同
        { cout << "Password or ID incorrect" << endl;
          continue;
        }//输入天数
        cin >> no_of_days;
        for (i=0; i < no_of_days; i++){//输入操作代码, 金额, 当日万元收益
          cin >> op_code >> money >> interest;
          switch (op_code){
              case 'S': //从银行向互联网金融帐户存入
              case 's': if (!ib_user.deposit(money)){
                            cout << "Bank balance not enough" << endl;
                            continue;
                         }
                         break;
               case 'T': //从互联网金融转入银行帐户
               case 't':if (!ib_user.withdraw(money)){
                            cout << "Internet bank balance not enough" << endl;
                            continue;
                         }
                         break;
               case 'D': //直接向银行帐户存款
               case 'd':ib_user.CBankCustomer::deposit(money);
                        break;
               case 'W': //直接从银行帐户取款
               case 'w':if (!ib_user.CBankCustomer::withdraw(money)){
                            cout << "Bank balance not enough" << endl;
                            continue;
                        }
                        break;
               default:cout << "Illegal input" << endl;
                       continue;
           }
           ib_user.setInterest(interest);
           ib_user.calculateProfit();//输出用户名,id//输出银行余额 //输出互联网金融账户余额
           ib_user.print();
           cout << endl;
        }
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
操作系统中的多生产者多消费者问题是一个经典的同步问题,它涉及到多个生产者和消费者同时访问一个有限缓冲区的情况。为了避免生产者和消费者之间的竞争条件和死锁问题,需要使用同步机制来协调它们之间的访问。下面是一种基于Python的解决方案: ```python import threading import time # 缓冲区大小 BUFFER_SIZE = 10 # 生产者线程 class ProducerThread(threading.Thread): def __init__(self, threadID, name, buffer): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.buffer = buffer def run(self): while True: # 获取锁 self.buffer.lock.acquire() # 如果缓冲区已满,等待 while self.buffer.isFull(): self.buffer.full.wait() # 生产一个物品 item = self.threadID self.buffer.put(item) print("Producer %s produced item %s" % (self.name, item)) # 释放锁 self.buffer.empty.notify() self.buffer.lock.release() # 等待一段时间 time.sleep(1) # 消费者线程 class ConsumerThread(threading.Thread): def __init__(self, threadID, name, buffer): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.buffer = buffer def run(self): while True: # 获取锁 self.buffer.lock.acquire() # 如果缓冲区为空,等待 while self.buffer.isEmpty(): self.buffer.empty.wait() # 消费一个物品 item = self.buffer.get() print("Consumer %s consumed item %s" % (self.name, item)) # 释放锁 self.buffer.full.notify() self.buffer.lock.release() # 等待一段时间 time.sleep(1) # 缓冲区类 class Buffer: def __init__(self): self.buffer = [] self.lock = threading.Lock() self.full = threading.Condition(self.lock) self.empty = threading.Condition(self.lock) # 判断缓冲区是否为空 def isEmpty(self): return len(self.buffer) == 0 # 判断缓冲区是否已满 def isFull(self): return len(self.buffer) == BUFFER_SIZE # 向缓冲区中添加一个物品 def put(self, item): self.buffer.append(item) # 从缓冲区中取出一个物品 def get(self): return self.buffer.pop() # 创建缓冲区 buffer = Buffer() # 创建生产者线程 for i in range(3): producer = ProducerThread(i, "P%d" % i, buffer) producer.start() # 创建消费者线程 for i in range(3): consumer = ConsumerThread(i, "C%d" % i, buffer) consumer.start() ``` 上述代码中,我们使用了Python中的线程和锁机制来实现多生产者多消费者问题。具体来说,我们定义了一个缓冲区类,其中包含了一个列表作为缓冲区,以及一个锁和两个条件变量。生产者线程和消费者线程分别继承自Python中的Thread类,并在run方法中实现了生产和消费的逻辑。在生产和消费的过程中,我们使用了锁和条件变量来保证线程之间的同步和互斥。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值