实验四

任务一:

代码:

 1 #include <iostream>
 2 
 3 using std::cout;
 4 using std::endl;
 5 
 6 // 类A的定义
 7 class A {
 8 public:
 9     A(int x0, int y0);
10     void display() const;
11 
12 private:
13     int x, y;
14 };
15 
16 A::A(int x0, int y0): x{x0}, y{y0} {
17 }
18 
19 void A::display() const {
20     cout << x << ", " << y << endl;
21 }
22 
23 // 类B的定义
24 class B {
25 public:
26     B(double x0, double y0);
27     void display() const;
28 
29 private:
30     double x, y;
31 };
32 
33 B::B(double x0, double y0): x{x0}, y{y0} {
34 }
35 
36 void B::display() const {
37     cout << x << ", " << y << endl;
38 }
39 
40 void test() {
41     cout << "测试类A: " << endl;
42     A a(3, 4);
43     a.display();
44 
45     cout << "\n测试类B: " << endl;
46     B b(3.2, 5.6);
47     b.display();
48 }
49 
50 int main() {
51     test();
52 }
View Code
 1 #include <iostream>
 2 #include <string>
 3 
 4 using std::cout;
 5 using std::endl;
 6 using std::string;
 7 
 8 // 定义类模板
 9 template<typename T>
10 class X{
11 public:
12     X(T x0, T y0);
13     void display();
14 
15 private:
16     T x, y;
17 };
18 
19 template<typename T>
20 X<T>::X(T x0, T y0): x{x0}, y{y0} {
21 }
22 
23 template<typename T>
24 void X<T>::display() {
25     cout << x << ", " << y << endl;
26 }
27 
28 
29 void test() {
30     cout << "测试1: 类模板X中的抽象类型T用int实例化" << endl;
31     X<int> x1(3, 4);
32     x1.display();
33     
34     cout << endl;
35 
36     cout << "测试2: 类模板X中的抽象类型T用double实例化" << endl;
37     X<double> x2(3.2, 5.6);
38     x2.display();
39 
40     cout << endl;
41 
42     cout << "测试3: 类模板X中的抽象类型T用string实例化" << endl;
43     X<string> x3("hello", "oop");
44     x3.display();
45 }
46 
47 int main() {
48     test();
49 }
View Code
 1 #include <complex>
 2 #include <vector>
 3 #include <array>
 4 
 5 int main() {
 6     using namespace std;
 7     
 8     complex<double> x1(5,3);        // complex类模板,特化到double类型
 9     vector<int> x2{1, 9, 8, 4};        // vector类模板,特化到int类型
10     array<int, 4> x3{1,9, 8, 4};    // array类模板,特化到int类型
11     // 其它略
12 }
View Code

模板类的关键在于此泛型的使用,之前在数据结构实验中使用深有体会创建一个mylist元素类型自己创建的时候传就行

任务二

代码:

  1 #include <iostream>
  2 #include <vector>
  3 #include <string>
  4 #include <algorithm>
  5 #include <numeric>
  6 #include <iomanip>
  7 
  8 using std::vector;
  9 using std::string;
 10 using std::cin;
 11 using std::cout;
 12 using std::endl;
 13 
 14 class GradeCalc: public vector<int> {
 15 public:
 16     GradeCalc(const string &cname, int size);      
 17     void input();                             // 录入成绩
 18     void output() const;                      // 输出成绩
 19     void sort(bool ascending = false);        // 排序 (默认降序)
 20     int min() const;                          // 返回最低分
 21     int max() const;                          // 返回最高分
 22     float average() const;                    // 返回平均分
 23     void info();                              // 输出课程成绩信息 
 24 
 25 private:
 26     void compute();     // 成绩统计
 27 
 28 private:
 29     string course_name;     // 课程名
 30     int n;                  // 课程人数
 31     vector<int> counts = vector<int>(5, 0);      // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100]
 32     vector<double> rates = vector<double>(5, 0); // 保存各分数段比例 
 33 };
 34 
 35 GradeCalc::GradeCalc(const string &cname, int size): course_name{cname}, n{size} {}   
 36 
 37 void GradeCalc::input() {
 38     int grade;
 39 
 40     for(int i = 0; i < n; ++i) {
 41         cin >> grade;
 42         this->push_back(grade);
 43     } 
 44 }  
 45 
 46 void GradeCalc::output() const {
 47     for(auto ptr = this->begin(); ptr != this->end(); ++ptr)
 48         cout << *ptr << " ";
 49     cout << endl;
 50 } 
 51 
 52 void GradeCalc::sort(bool ascending) {
 53     if(ascending)
 54         std::sort(this->begin(), this->end());
 55     else
 56         std::sort(this->begin(), this->end(), std::greater<int>());
 57 }  
 58 
 59 int GradeCalc::min() const {
 60     return *std::min_element(this->begin(), this->end());
 61 }  
 62 
 63 int GradeCalc::max() const {
 64     return *std::max_element(this->begin(), this->end());
 65 }    
 66 
 67 float GradeCalc::average() const {
 68     return std::accumulate(this->begin(), this->end(), 0) * 1.0 / n;
 69 }   
 70 
 71 void GradeCalc::compute() {
 72     for(int grade: *this) {
 73         if(grade < 60)
 74             counts.at(0)++;
 75         else if(grade >= 60 && grade < 70)
 76             counts.at(1)++;
 77         else if(grade >= 70 && grade < 80)
 78             counts.at(2)++;
 79         else if(grade >= 80 && grade < 90)
 80             counts.at(3)++;
 81         else if(grade >= 90)
 82             counts.at(4)++;
 83     }
 84 
 85     for(int i = 0; i < rates.size(); ++i)
 86         rates.at(i) = counts.at(i) * 1.0 / n;
 87 }
 88 
 89 void GradeCalc::info()  {
 90     cout << "课程名称:\t" << course_name << endl;
 91     cout << "排序后成绩: \t";
 92     sort();  output();
 93     cout << "最高分:\t" << max() << endl;
 94     cout << "最低分:\t" << min() << endl;
 95     cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl;
 96     
 97     compute();  // 统计各分数段人数、比例
 98 
 99     vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"};
100     for(int i = tmp.size()-1; i >= 0; --i)
101         cout << tmp[i] << "\t: " << counts[i] << "人\t" 
102              << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 
103 } 
104 ---------------------------------------------------------------------------------------
105 #include "a.hpp"
106 #include <iomanip>
107 
108 void test() {
109     int n;
110     cout << "输入班级人数: ";
111     cin >> n;
112 
113     GradeCalc c1("OOP", n);
114 
115     cout << "录入成绩: " << endl;;
116     c1.input();
117     cout << "输出成绩: " << endl;
118     c1.output();
119 
120     cout << string(20, '*') + "课程成绩信息"  + string(20, '*') << endl;
121     c1.info();
122 }
123 
124 int main() {
125     test();
126 }
View Code

 

截图

 

任务三

代码

  1 #include <iostream>
  2 #include <vector>
  3 #include <string>
  4 #include <algorithm>
  5 #include <numeric>
  6 #include <iomanip>
  7 
  8 using std::vector;
  9 using std::string;
 10 using std::cin;
 11 using std::cout;
 12 using std::endl;
 13 
 14 class GradeCalc {
 15 public:
 16     GradeCalc(const string &cname, int size);      
 17     void input();                             // 录入成绩
 18     void output() const;                      // 输出成绩
 19     void sort(bool ascending = false);        // 排序 (默认降序)
 20     int min() const;                          // 返回最低分
 21     int max() const;                          // 返回最高分
 22     float average() const;                    // 返回平均分
 23     void info();                              // 输出课程成绩信息 
 24 
 25 private:
 26     void compute();     // 成绩统计
 27 
 28 private:
 29     string course_name;     // 课程名
 30     int n;                  // 课程人数
 31     vector<int> grades;     // 课程成绩
 32     vector<int> counts = vector<int>(5, 0);      // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100]
 33     vector<double> rates = vector<double>(5, 0); // 保存各分数段比例 
 34 };
 35 
 36 GradeCalc::GradeCalc(const string &cname, int size): course_name{cname}, n{size} {}   
 37 
 38 void GradeCalc::input() {
 39     int grade;
 40 
 41     for(int i = 0; i < n; ++i) {
 42         cin >> grade;
 43         grades.push_back(grade);
 44     } 
 45 }  
 46 
 47 void GradeCalc::output() const {
 48     for(int grade: grades)
 49         cout << grade << " ";
 50     cout << endl;
 51 } 
 52 
 53 void GradeCalc::sort(bool ascending) {
 54     if(ascending)
 55         std::sort(grades.begin(), grades.end());
 56     else
 57         std::sort(grades.begin(), grades.end(), std::greater<int>());
 58         
 59 }  
 60 
 61 int GradeCalc::min() const {
 62     return *std::min_element(grades.begin(), grades.end());
 63 }  
 64 
 65 int GradeCalc::max() const {
 66     return *std::max_element(grades.begin(), grades.end());
 67 }    
 68 
 69 float GradeCalc::average() const {
 70     return std::accumulate(grades.begin(), grades.end(), 0) * 1.0 / n;
 71 }   
 72 
 73 void GradeCalc::compute() {
 74     for(int grade: grades) {
 75         if(grade < 60)
 76             counts.at(0)++;
 77         else if(grade >= 60 && grade < 70)
 78             counts.at(1)++;
 79         else if(grade >= 70 && grade < 80)
 80             counts.at(2)++;
 81         else if(grade >= 80 && grade < 90)
 82             counts.at(3)++;
 83         else if(grade >= 90)
 84             counts.at(4)++;
 85     }
 86 
 87     for(int i = 0; i < rates.size(); ++i)
 88         rates.at(i) = counts.at(i) *1.0 / n;
 89 }
 90 
 91 void GradeCalc::info()  {
 92     cout << "课程名称:\t" << course_name << endl;
 93     cout << "排序后成绩: \t";
 94     sort();  output();
 95     cout << "最高分:\t" << max() << endl;
 96     cout << "最低分:\t" << min() << endl;
 97     cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl;
 98     
 99     compute();  // 统计各分数段人数、比例
100 
101     vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"};
102     for(int i = tmp.size()-1; i >= 0; --i)
103         cout << tmp[i] << "\t: " << counts[i] << "人\t" 
104              << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 
105 } 
106 
107 
108 
109 #include "GradeCalc.hpp"
110 #include <iomanip>
111 
112 void test() {
113     int n;
114     cout << "输入班级人数: ";
115     cin >> n;
116 
117     GradeCalc c1("OOP", n);
118 
119     cout << "录入成绩: " << endl;;
120     c1.input();
121     cout << "输出成绩: " << endl;
122     c1.output();
123 
124     cout << string(20, '*') + "课程成绩信息"  + string(20, '*') << endl;
125     c1.info();
126 }
127 
128 int main() {
129     test();
130 }
View Code

 

截图

 

任务四

代码

  1 #include <iostream>
  2 #include <string>
  3 #include <limits>
  4 
  5 using namespace std;
  6 
  7 void test1() {
  8     string s1, s2;
  9     cin >> s1 >> s2;  // cin: 从输入流读取字符串, 碰到空白符(空格/回车/Tab)即结束
 10     cout << "s1: " << s1 << endl;
 11     cout << "s2: " << s2 << endl;
 12 }
 13 
 14 void test2() {
 15     string s1, s2;
 16     getline(cin, s1);  // getline(): 从输入流中提取字符串,直到遇到换行符
 17     getline(cin, s2);
 18     cout << "s1: " << s1 << endl;
 19     cout << "s2: " << s2 << endl;
 20 }
 21 
 22 void test3() {
 23     string s1, s2;
 24     getline(cin, s1, ' '); //从输入流中提取字符串,直到遇到指定分隔符
 25     getline(cin, s2);
 26     cout << "s1: " << s1 << endl;
 27     cout << "s2: " << s2 << endl;
 28 }
 29 
 30 int main() {
 31     cout << "测试1: 使用标准输入流对象cin输入字符串" << endl;
 32     test1();
 33     cout << endl;
 34 
 35     cin.ignore(numeric_limits<streamsize>::max(), '\n');
 36 
 37     cout << "测试2: 使用函数getline()输入字符串" << endl;
 38     test2();
 39     cout << endl;
 40 
 41     cout << "测试3: 使用函数getline()输入字符串, 指定字符串分隔符" << endl;
 42     test3();
 43 }
 44 
 45 
 46 
 47 #include <iostream>
 48 #include <string>
 49 #include <vector>
 50 #include <limits>
 51 
 52 using namespace std;
 53 
 54 void output(const vector<string> &v) {
 55     for(auto &s: v)
 56         cout << s << endl;
 57 }
 58 
 59 void test() {
 60     int n;
 61     while(cout << "Enter n: ", cin >> n) {
 62         vector<string> v1;
 63 
 64         for(int i = 0; i < n; ++i) {
 65             string s;
 66             cin >> s;
 67             v1.push_back(s);
 68         }
 69 
 70         cout << "output v1: " << endl;
 71         output(v1); 
 72         cout << endl;
 73     }
 74 }
 75 
 76 int main() {
 77     cout << "测试: 使用cin多组输入字符串" << endl;
 78     test();
 79 }
 80 
 81 
 82 
 83 #include <iostream>
 84 #include <string>
 85 #include <vector>
 86 #include <limits>
 87 
 88 using namespace std;
 89 
 90 void output(const vector<string> &v) {
 91     for(auto &s: v)
 92         cout << s << endl;
 93 }
 94 
 95 void test() {
 96     int n;
 97     while(cout << "Enter n: ", cin >> n) {
 98         cin.ignore(numeric_limits<streamsize>::max(), '\n');
 99 
100         vector<string> v2;
101 
102         for(int i = 0; i < n; ++i) {
103             string s;
104             getline(cin, s);
105             v2.push_back(s);
106         }
107         cout << "output v2: " << endl;
108         output(v2); 
109         cout << endl;
110     }
111 }
112 
113 int main() {
114     cout << "测试: 使用函数getline()多组输入字符串" << endl;
115     test();
116 }
View Code

截图

 如果去掉那一行代码缓冲区的换行在test2方法执行时会直接被调用

 

 

 getline() 函数的行为与 cin >> s 不同,它不会自动跳过前导的空白字符,而是从当前位置开始读取字符,直到遇到指定的分隔符(默认是换行符 '\n')。因此,在使用 getline() 时,如果输入缓冲区中有未处理的换行符(例如,之前的 cin 操作留下的),这些换行符会被 getline() 读取,导致预期的输入行为不正确。

 cin读取时会跳过前面的换行符,但是getline不会,然而getline却会处理输入最后的换行符确保不会被下一次读到

 任务五

代码

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include <algorithm>
 5 #include <numeric>
 6 #include <iomanip>
 7 
 8 using namespace std;
 9 
10 template<typename T>
11 class GameResourceManager{
12     public:
13         GameResourceManager(T num):val{num}{};
14         T get(){
15             return val;
16         }
17         void update(T temp){
18             val += temp;
19             if(val < 0){
20                 val = 0;
21             }
22         }
23         
24     private:
25         T val;
26 };
27 
28 
29 
30 #include "a.hpp"
31 #include <iostream>
32 
33 using std::cout;
34 using std::endl;
35 
36 void test1() {
37     GameResourceManager<float> HP_manager(99.99);
38     cout << "当前生命值: " << HP_manager.get() << endl;
39     HP_manager.update(9.99);
40     cout << "增加9.99生命值后, 当前生命值: " << HP_manager.get() << endl;
41     HP_manager.update(-999.99);
42     cout <<"减少999.99生命值后, 当前生命值: " << HP_manager.get() << endl;
43 }
44 
45 void test2() {
46     GameResourceManager<int> Gold_manager(100);
47     cout << "当前金币数量: " << Gold_manager.get() << endl;
48     Gold_manager.update(50);
49     cout << "增加50个金币后, 当前金币数量: " << Gold_manager.get() << endl;
50     Gold_manager.update(-99);
51     cout <<"减少99个金币后, 当前金币数量: " << Gold_manager.get() << endl;
52 }
53 
54 
55 int main() {
56     cout << "测试1: 用float类型对类模板GameResourceManager实例化" << endl;
57     test1();
58     cout << endl;
59 
60     cout << "测试2: 用int类型对类模板GameResourceManager实例化" << endl;
61     test2();
62 }
View Code

 

截图

 任务六

代码

 1 #include <string>
 2 #include <iostream>
 3 
 4 class Info {
 5 private:
 6     std::string nickname;  // 昵称
 7     std::string contact;   // 联系方式
 8     std::string city;      // 所在城市
 9     int n;                 // 预定参加人数
10 
11 public:
12     // 带参数的构造函数
13     Info(const std::string& nickname, const std::string& contact, const std::string& city, int n)
14         : nickname(nickname), contact(contact), city(city), n(n) {}
15 
16     // 显示信息
17     void display() const {
18         std::cout << "昵称: " << nickname << std::endl;
19         std::cout << "联系方式: " << contact << std::endl;
20         std::cout << "所在城市: " << city << std::endl;
21         std::cout << "预定参加人数: " << n << std::endl;
22     }
23 
24     // 获取预定参加人数
25     int getN() const {
26         return n;
27     }
28 
29     // 更新预定信息
30     void update(const std::string& newNickname, const std::string& newContact, const std::string& newCity, int newN) {
31         nickname = newNickname;
32         contact = newContact;
33         city = newCity;
34         n = newN;
35     }
36 };
37 
38 
39 #include "a.hpp"
40 #include <iostream>
41 
42 using std::cout;
43 using std::endl;
44 
45 void test1() {
46     GameResourceManager<float> HP_manager(99.99);
47     cout << "当前生命值: " << HP_manager.get() << endl;
48     HP_manager.update(9.99);
49     cout << "增加9.99生命值后, 当前生命值: " << HP_manager.get() << endl;
50     HP_manager.update(-999.99);
51     cout <<"减少999.99生命值后, 当前生命值: " << HP_manager.get() << endl;
52 }
53 
54 void test2() {
55     GameResourceManager<int> Gold_manager(100);
56     cout << "当前金币数量: " << Gold_manager.get() << endl;
57     Gold_manager.update(50);
58     cout << "增加50个金币后, 当前金币数量: " << Gold_manager.get() << endl;
59     Gold_manager.update(-99);
60     cout <<"减少99个金币后, 当前金币数量: " << Gold_manager.get() << endl;
61 }
62 
63 
64 int main() {
65     cout << "测试1: 用float类型对类模板GameResourceManager实例化" << endl;
66     test1();
67     cout << endl;
68 
69     cout << "测试2: 用int类型对类模板GameResourceManager实例化" << endl;
70     test2();
71 }
View Code

截图

 任务七

代码

  1 #include "account.h"
  2 #include <cmath>
  3 #include <iostream>
  4 using namespace std;
  5 
  6 double Account::total = 0;
  7 
  8 Account::Account(const Date& date, const string& id) : id{id}, balance{0} {
  9     date.show();
 10     cout << "\t#" << id << " created" << endl;
 11 }
 12 
 13 void Account::record(const Date& date, double amount, const string& desc) {
 14     amount = floor(amount * 100 + 0.5) / 100;
 15     balance += amount;
 16     total += amount;
 17     date.show();
 18     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
 19 }
 20 
 21 void Account::show() const {
 22     cout << id << "\tBalance: " << balance;
 23 }
 24 
 25 void Account::error(const string& msg) const {
 26     cout << "Error(#" << id << "): " << msg << endl;
 27 }
 28 
 29 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate)
 30     : Account(date, id), rate(rate), acc(date, 0) {}
 31 
 32 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) {
 33     record(date, amount, desc);
 34     acc.change(date, getBalance());
 35 }
 36 
 37 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) {
 38     if (amount > getBalance()) {
 39         error("not enough money");
 40     } else {
 41         record(date, -amount, desc);
 42         acc.change(date, getBalance());
 43     }
 44 }
 45 
 46 void SavingsAccount::settle(const Date& date) {
 47     double interest = acc.getSum(date) * rate / date.distance(Date(date.getYear() - 1, 1, 1));
 48     if (interest != 0) record(date, interest, "interest");
 49     acc.reset(date, getBalance());
 50 }
 51 
 52 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee)
 53     : Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) {}
 54 
 55 void CreditAccount::deposit(const Date& date, double amount, const string& desc) {
 56     record(date, amount, desc);
 57     acc.change(date, getDebt());
 58 }
 59 
 60 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) {
 61     if (amount - getBalance() > credit) {
 62         error("not enough credit");
 63     } else {
 64         record(date, -amount, desc);
 65         acc.change(date, getDebt());
 66     }
 67 }
 68 
 69 void CreditAccount::settle(const Date& date) {
 70     double interest = acc.getSum(date) * rate;
 71     if (interest != 0) record(date, interest, "interest");
 72     if (date.getMonth() == 1) record(date, -fee, "annual fee");
 73     acc.reset(date, getDebt());
 74 }
 75 
 76 void CreditAccount::show() const {
 77     Account::show();
 78     cout << "\tAvailable credit: " << getAvailableCredit();
 79 }
 80 
 81 #pragma once
 82 #ifndef ACCOUNT_H
 83 #define ACCOUNT_H
 84 
 85 #include "date.h"
 86 #include "accumulator.h"
 87 #include <string>
 88 
 89 class Account {
 90 private:
 91     std::string id;
 92     double balance;
 93     static double total;
 94 
 95 protected:
 96     Account(const Date& date, const std::string& id);
 97     void record(const Date& date, double amount, const std::string& desc);
 98     void error(const std::string& msg) const;
 99 
100 public:
101     const std::string& getId() const { return id; }
102     double getBalance() const { return balance; }
103     static double getTotal() { return total; }
104 
105     void show() const;
106 };
107 
108 class SavingsAccount : public Account {
109 private:
110     Accumulator acc;
111     double rate;
112 
113 public:
114     SavingsAccount(const Date& date, const std::string& id, double rate);
115     double getRate() const { return rate; }
116 
117     void deposit(const Date& date, double amount, const std::string& desc);
118     void withdraw(const Date& date, double amount, const std::string& desc);
119     void settle(const Date& date);
120 };
121 
122 class CreditAccount : public Account {
123 private:
124     Accumulator acc;
125     double credit;
126     double rate;
127     double fee;
128 
129     double getDebt() const {
130         double balance = getBalance();
131         return (balance < 0 ? balance : 0);
132     }
133 
134 public:
135     CreditAccount(const Date& date, const std::string& id, double credit, double rate, double fee);
136     double getCredit() const { return credit; }
137     double getRate() const { return rate; }
138     double getAvailableCredit() const {
139         if (getBalance() < 0)
140             return credit + getBalance();
141         else
142             return credit;
143     }
144 
145     void deposit(const Date& date, double amount, const std::string& desc);
146     void withdraw(const Date& date, double amount, const std::string& desc);
147     void settle(const Date& date);
148     void show() const;
149 };
150 
151 #endif // ACCOUNT_H
152 
153 
154 #pragma once
155 #ifndef ACCUMULATOR_H
156 #define ACCUMULATOR_H
157 
158 #include "date.h"
159 
160 class Accumulator {
161 private:
162     Date lastDate;
163     double value;
164     double sum;
165 
166 public:
167     Accumulator(const Date& date, double value) : lastDate(date), value(value), sum{0} {}
168 
169     double getSum(const Date& date) const {
170         return sum + value * date.distance(lastDate);
171     }
172 
173     void change(const Date& date, double value) {
174         sum = getSum(date);
175         lastDate = date;
176         this->value = value;
177     }
178 
179     void reset(const Date& date, double value) {
180         lastDate = date;
181         this->value = value;
182         sum = 0;
183     }
184 };
185 
186 #endif // ACCUMULATOR_H
187 
188 
189 #include "date.h"
190 #include <iostream>
191 #include <cstdlib>
192 using namespace std;
193 
194 namespace {
195     const int DAYS_BEFORE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 };
196 }
197 
198 Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
199     if (day <= 0 || day > getMaxDay()) {
200         cout << "Invalid date:";
201         show();
202         cout << endl;
203         exit(1);
204     }
205     int years = year - 1;
206     totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;
207     if (isLeapYear() && month > 2) totalDays++;
208 }
209 
210 int Date::getMaxDay() const {
211     if (isLeapYear() && month == 2)
212         return 29;
213     else
214         return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
215 }
216 
217 void Date::show() const {
218     cout << getYear() << "-" << getMonth() << "-" << getDay();
219 }
220 
221 
222 #ifndef __DATE_H__
223 #define __DATE_H__
224 
225 class Date {
226 private:
227     int year;
228     int month;
229     int day;
230     int totalDays;
231 
232 public:
233     Date(int year, int month, int day);
234     int getYear() const { return year; }
235     int getMonth() const { return month; }
236     int getDay() const { return day; }
237     int getMaxDay() const;
238     bool isLeapYear() const {
239         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
240     }
241     void show() const;
242     int distance(const Date& date) const {
243         return totalDays - date.totalDays;
244     }
245 };
246 
247 #endif // __DATE_H__
View Code

截图

 

posted @ 2024-11-24 21:49  枯基Evan  阅读(4)  评论(0编辑  收藏  举报