首页 > 其他分享 >实验五-继承和多态

实验五-继承和多态

时间:2023-12-03 18:55:24浏览次数:29  
标签:std const string 继承 double 多态 Date 实验 date

pets.hpp

 1 #ifndef PETS_HPP
 2 #define PETS_HPP
 3 
 4 #include <iostream>
 5 #include <string>
 6 
 7 class MachinePets {
 8 protected:
 9     std::string nickname;
10 public:
11     MachinePets(const std::string s) : nickname(s) {}
12     std::string get_nickname() { return nickname; }
13     virtual std::string talk() = 0;
14 };
15 
16 class PetCats : public MachinePets {
17 public:
18     PetCats(const std::string s) : MachinePets(s) {}
19     std::string talk() { return "喵喵!"; }
20 };
21 
22 class PetDogs : public MachinePets {
23 public:
24     PetDogs(const std::string s) : MachinePets(s) {}
25     std::string talk() { return "旺旺!"; }
26 };
27 
28 #endif
View Code

 

task3.cpp

 1 #include <iostream>
 2 #include "pets.hpp"
 3 
 4 void play(MachinePets &obj) {
 5     std::cout << obj.get_nickname() << " says " << obj.talk() << std::endl;
 6 }
 7 
 8 void test() {
 9     PetCats cat("miku");
10     PetDogs dog("da huang");
11 
12     play( cat );
13     play( dog );
14 }
15 
16 int main() {
17     test();
18 }
View Code

 

运行结果截图

 

Person.hpp
 1 #ifndef PERSON_HPP
 2 #define PERSON_HPP
 3 
 4 #include <iostream>
 5 
 6 class Person {
 7 private:
 8     std::string name;
 9     std::string telephone;
10     std::string email;
11 public:
12     Person() = default;
13     Person(const std::string& name, const std::string& telephone, const std::string& email = "") 
14         : name(name), telephone(telephone), email(email) {}
15     Person(const Person& other) = default;
16 
17     void update_telephone() {
18         std::cout << "请输入新的手机号码: ";
19         std::cin >> telephone;
20     }
21 
22     void update_email() {
23         std::cout << "请输入新的邮箱地址: ";
24         std::cin >> email;
25     }
26 
27     friend std::ostream& operator<<(std::ostream& os, const Person& p) {
28         os << "姓名: " << p.name << "\t手机号码: " << p.telephone << "\t邮箱: " << p.email;
29         return os;
30     }
31 
32     friend std::istream& operator>>(std::istream& is, Person& p) {
33         
34         is >> p.name;
35        
36         is >> p.telephone;
37         
38         is >> p.email;
39         return is;
40     }
41 
42     friend bool operator==(const Person& p1, const Person& p2) {
43         return (p1.name == p2.name) && (p1.telephone == p2.telephone);
44     }
45 };
46 
47 #endif
View Code

 

task4.cpp
 1 #include <iostream>
 2 #include <vector>
 3 #include "Person.hpp"
 4 
 5 void test() {
 6     using namespace std;
 7 
 8     vector<Person> phone_book;
 9     Person p;
10 
11     cout << "输入一组联系人的联系方式,E直至按下Ctrl+Z终止\n";
12     while(cin >> p) 
13         phone_book.push_back(p);
14     
15     cout << "\n更新phone_book中索引为0的联系人的手机号、邮箱:\n";
16     phone_book.at(0).update_telephone();
17     phone_book.at(0).update_email();
18 
19     cout << "\n测试两个联系人是否是同一个:\n";
20     cout << boolalpha << (phone_book.at(0) == phone_book.at(1)) << endl;
21 }
22 
23 int main() {
24     test();
25 }
View Code

 

运行结果截图

 


date.h
 1 class Date
 2 {
 3 private:
 4     int year;
 5     int month;
 6     int day;
 7     int totalDays;
 8 public:
 9     Date(int year, int month, int day);
10     int getYear() const { return year; }
11     int getMonth() const { return month; }
12     int getDay() const { return day; }
13     int getMaxDay() const;
14     bool isLeapYear() const
15     {
16         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
17     }
18     void show() const;
19     int operator-(const Date& date) const
20     {
21         return totalDays - date.totalDays;
22     }
23 };
View Code

 


date.cpp
 1 #include"date.h"
 2 #include<iostream>
 3 #include<cstdlib>
 4 using namespace std;
 5 namespace
 6 {
 7     const int DAYS_BEFORE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 };
 8 }
 9 Date::Date(int year, int month, int day) :year(year), month(month), day(day)
10 {
11     if (day <= 0 || day > getMaxDay())
12     {
13         cout << "INvalid date:";
14         show();
15         cout << endl;
16         exit(1);
17     }
18     int years = year - 1;
19     totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;
20     if (isLeapYear() && month > 2) totalDays++;
21 }
22 int Date::getMaxDay() const
23 {
24     if (isLeapYear() && month == 2)
25         return 29;
26     else
27         return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
28 }
29 void Date::show() const
30 {
31     cout << getYear() << "-" << getMonth() << "-" << getDay();
32 }
View Code

 


accumulator.h
#include"date.h"
class Accumulator
{
private:
    Date lastDate;
    double value;
    double sum;
public:
    Accumulator(const Date& date, double value) :lastDate(date), value(value), sum(0) {}
    double getSum(const Date& date) const
    {
        return sum + value * (date - lastDate);
    }
    void change(const Date& date, double value)
    {
        sum = getSum(date);
        lastDate = date; this->value = value; sum = 0;
    }
    void reset(const Date& date, double value)
    {
        lastDate = date; this->value = value;
    }
};
View Code

 


account.h
 1 #include"date.h"
 2 #include"accumulator.h"
 3 #include<string>
 4 class Account
 5 {
 6 private:
 7     std::string id;
 8     double balance;
 9     static double total;
10 protected:
11     Account(const Date& date, const std::string& id);
12     void record(const Date& date, double amount, const std::string& desc);
13     void error(const std::string& msg) const;
14 public:
15     const std::string& getId() const { return id; }
16     double getBalance() const { return balance; }
17     static double getToal() { return total; }
18     virtual void deposit(const Date& date, double amount, const std::string& desc) = 0;
19     virtual void withdraw(const Date& date, double amount, const std::string& desc) = 0;
20     virtual void settle(const Date& date);
21     virtual void show() const;
22 };
23 class SavingsAccount :public Account
24 {
25 private:
26     Accumulator acc;
27     double rate;
28 public:
29     SavingsAccount(const Date& date, const std::string& id, double rate);
30     double getRate() const { return rate; }
31     void deposit(const Date& date, double amount, const std::string& desc);
32     void withdraw(const Date& date, double amount, const std::string& desc);
33     void settle(const Date& date);
34 };
35 class CreditAccount :public Account
36 {
37 private:
38     Accumulator acc;
39     double credit;
40     double rate;
41     double fee;
42     double getDebt() const
43     {
44         double balance = getBalance();
45         return(balance < 0 ? balance : 0);
46     }
47 public:
48     CreditAccount(const Date& date, const std::string& id, double credit, double rate, double fee);
49     double getCredit() const { return credit; }
50     double getRate() const { return rate; }
51     double getFee() const { return fee; }
52     double getAvailableCredit() const {
53         if (getBalance() < 0)
54             return credit + getBalance();
55         else
56             return credit;
57     }
58     void deposit(const Date& date, double amount, const std::string& desc);
59     void withdraw(const Date& date, double amount, const std::string& desc);
60     void settle(const Date& date);
61     void show() const;
62 };
View Code

 


account.cpp
 1 #include"account.h"
 2 #include<cmath>
 3 #include<iostream>
 4 using namespace std;
 5 double Account::total = 0;
 6 Account::Account(const Date& date, const std::string& id) :id(id), balance(0)
 7 {
 8     date.show(); cout << "\t#" << id << "created" << endl;
 9 }
10 void Account::record(const Date& date, double amount, const string& desc)
11 {
12     amount = floor(amount * 100 + 0.5) / 100;
13     balance += amount; total += amount;
14     date.show();
15     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
16 }
17 void Account::show() const { cout << id << "\tBalance:" << balance; }
18 void Account::error(const string& msg) const
19 {
20     cout << "Error(#" << id << "):" << msg << endl;
21 }
22 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) :Account(date, id), rate(rate), acc(date, 0) {
23 }
24 void SavingsAccount::deposit(const Date& date, double amount, const string& desc)
25 {
26     record(date, amount, desc);
27     acc.change(date, getBalance());
28 }
29 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc)
30 {
31     if (amount > getBalance())
32     {
33         error("not enough money");
34     }
35     else
36     {
37         record(date, -amount, desc);
38         acc.change(date, getBalance());
39     }
40 }
41 void SavingsAccount::settle(const Date& date)
42 {
43     if (date.getMonth() == 1)
44     {
45         double interest = acc.getSum(date) * rate / (date - Date(date.getYear() - 1, 1, 1));
46         if (interest != 0) record(date, interest, "interest");
47         acc.reset(date, getBalance());
48     }
49 }
50 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee) :Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) {
51 }
52 void CreditAccount::deposit(const Date& date, double amount, const string& desc)
53 {
54     record(date, amount, desc);
55     acc.change(date, getDebt());
56 }
57 void CreditAccount::withdraw(const Date& date, double amount, const string& desc)
58 {
59     if (amount - getBalance() > credit)
60     {
61         error("not enough credit");
62     }
63     else
64     {
65         record(date, -amount, desc);
66         acc.change(date, getDebt());
67     }
68 }
69 void CreditAccount::settle(const Date& date)
70 {
71     double interest = acc.getSum(date) * rate;
72     if (interest != 0) record(date, interest, "interest");
73     if (date.getMonth() == 1) record(date, -fee, "annual fee");
74     acc.reset(date, getDebt());
75 }
76 void CreditAccount::show() const
77 {
78     Account::show();
79     cout << "\tAvailable credit:" << getAvailableCredit();
80 }
View Code

 


8_8.cpp
 1 #include"account.h"
 2 #include<iostream>
 3 using namespace std;
 4 int main()
 5 {
 6     Date date(2008, 11, 1);
 7     SavingsAccount sa1(date, "s3755217", 0.015);
 8     SavingsAccount sa2(date, "02342342", 0.015);
 9     CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
10     Account* accounts[] = { &sa1,&sa2,&ca };
11     const int n = sizeof(accounts) / sizeof(Account*);
12     cout << "(d)deposit(w)withdraw(s)show(c)change day(n) next month(e) exit" << endl;
13     char cmd;
14     do {
15         date.show();
16         cout << "\tTotal:" << Account::getToal() << "\tcommand";
17         int index, day;
18         double amount; string desc;
19         cin >> cmd;
20         switch (cmd)
21         {
22         case'd':
23             cin >> index >> amount;
24             getline(cin, desc);
25             accounts[index]->deposit(date, amount, desc);
26             break;
27         case'w':
28             cin >> index >> amount;
29             getline(cin, desc);
30             accounts[index]->withdraw(date, amount, desc);
31             break;
32         case's':
33             for (int i = 0; i < n; i++)
34             {
35                 cout << "[" << i << "]";
36                 accounts[i]->show();
37                 cout << endl;
38             }
39             break;
40         case'c':
41             cin >> day;
42             if (day << date.getDay())
43                 cout << "You cannot specify a previous day";
44             else if (day > date.getMaxDay())
45                 cout << "Invalid day";
46             else
47                 date = Date(date.getYear(), date.getMonth(), day);
48             break;
49         case'n':
50             if (date.getMonth() == 12)
51                 date = Date(date.getYear() + 1, 1, 1);
52             else
53                 date = Date(date.getYear(), date.getMonth() + 1, 1);
54             for (int i = 0; i < n; i++)
55                 accounts[i]->settle(date);
56             break;
57         }
58     } while (cmd != 'e');
59     return 0;
60 }
View Code

 

运行结果截图

 

 

标签:std,const,string,继承,double,多态,Date,实验,date
From: https://www.cnblogs.com/chenxiaolong202083290491/p/17873547.html

相关文章

  • 实验5 ———
    1.1找到最大值和最小值数组x的第一个元素x[0]的值1.2最大值所在元素的地址不,地址不能交换 2.11__23   sizeof(s1)计算的是数组s1在内存中所占用的字节数strlen(s1)统计的是字符串s1中的字符数2__不能  未分配地址3__能2.21__s1不再是一个数组,而......
  • 实验5
    任务5:1#ifndef__DATE_H__2#define__DATE_H__3classDate{4private:5intyear;6intmonth;7intday;8inttotalDays;9public:10Date(intyear,intmonth,intyear);11......
  • 实验5 继承和多态
    四、实验结论实验任务3pets.hpp#pragmaonce#include<iostream>#include<string>usingnamespacestd;classMachinePets{public:MachinePets(conststring&s="");stringget_nickname()const;public:virtualstringtalk()......
  • 实验5
    #include<iostream>#include<string>usingnamespacestd;classMachinePets{private:stringnickname;public:MachinePets(conststrings):nickname{s}{}stringget_nickname()const{returnnickname;}virtualstringtalk()......
  • 实验五
     找出最大最小值 指向x【0】的地址 返回最大值的地址  sizeof计算数据类型所占据的空间,比如字节长度,而strlen计算字符串的长度,从第一个字符遇到结束符停止。sizeof包含“\0”,strlen则不计算。     #defineN80voidencoder(char*str);//函数声......
  • 百度api实验总结
    通过这次实验还是反映了之前讲到的,修改代码必须要建立在看懂的情况下,同样避免错误也是一样的,刚开始拿到这样一个json返回值的时候很蒙,饭后想到了之前看到的提取其中的值,我就说查一下吧查到了不过是python的不过原理都一样我就说改改吧但是不成功,用为python的json包导进去很简单,直......
  • 实验5
    3.hpp#include<iostream>#include<string>usingnamespacestd;classMachinePets{public:MachinePets(conststrings);MachinePets();stringget_nickname()const;public:virtualstringtalk()=0;protected:......
  • C0P8000计算机组成原理实验系统24位控制位功能
    因为做到了这个课设所以存一下相关内容24位控制位XRD:外部设备读信号,当给出了外设的地址后,输出此信号,从指定外设读数据。EMWR:程序存储器EM写信号。EMRD:程序存储器EM读信号。PCOE:将程序计数器PC的值送到地址总线ABUS上。EMEN:将程序存储器EM与数据总线DBUS......
  • 实验五
    任务一publisher.hpp1#pragmaonce23#include<iostream>4#include<string>56usingstd::cout;7usingstd::endl;8usingstd::string;910//发行/出版物类:Publisher(抽象类)11classPublisher{12public:13Publisher(conststr......
  • .Net实验一 语言基础
    一、实验目的熟悉VisualStido.NET实验环境;掌握控制台程序的编写方法;掌握C#程序设计语言的语法基础;掌握控制语句和数组的使用。二、实验要求根据题目要求,编写C#程序,并将程序代码和运行结果写入实验报告。三、实验内容编写一个控制台应用程序,输入三角形或者长方形边长,计......