类的封装
面向对象有三大特点, 封装,继承,多态
C++将struct 做了功能的增强,struct实际上就是一个class
只不过struct的类的内部,默认的访问控制权限是public
class 的类的内部,默认的访问控制权限是private
输入年月日,并判断是否是闰年
封装前
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #define _CRT_SECURE_NO_WARNINGS #include <iostream>
using namespace std;
struct Date { int year; int month; int day; };
void init(struct Date & date) { cout << "year, month, day" << endl; cin >> date.year; cin >> date.month; cin >> date.day; }
void printDate(struct Date &date) { cout << "日期是" << date.year << "年" << date.month << "月" << date.day << "日" << endl; }
bool isLeapYear(struct Date &date) { if (((date.year % 4 == 0) && (date.year % 100 != 0)) || (date.year % 400 == 0)) { return true; } else { return false; } }
void test1() { struct Date date;
init(date);
printDate(date);
if (isLeapYear(date) == true) { cout << "是闰年" << endl; } else { cout << "不是闰年" << endl; } } int main() { test1(); return 0; }
|
封装后
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #define _CRT_SECURE_NO_WARNINGS #include <iostream>
using namespace std; class MyDate { public:
int getYear() { return year; }
void init() { cout << "year, month, day" << endl; cin >> year; cin >> month; cin >> day; }
bool isLeapYear() { if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { return true; } else { return false; } }
void printDate() { cout << "日期是" << year << "年" << month << "月" << day << "日" << endl; }
protected: private: int month; int day; int year; };
void test2() { MyDate date;
date.init(); if (date.isLeapYear() == true) { cout << "是闰年" << endl; } else { cout << "不是闰年" << endl; }
cout << "年" << date.getYear() << endl;
}
int main(void) {
test2();
return 0; }
|