c语言风格的封装 数据放在一起,以引用和指针的方式传给行为
c++ 认为封装不彻底
1数据和行为分开 对外提供接口
2没有权限设置
看看struct的一个例子
1 //data.h 2 3 //c语言风格的封装 数据放在一起,以引用和指针的方式传给行为 4 //c++ 认为封装不彻底 5 //1数据和行为分开 对外提供接口 6 //2没有权限设置 7 8 struct Date 9 { 10 int year; 11 int month; 12 int day; 13 }; 14 15 16 void init(Date &d); 17 void print(Date &d); 18 bool isLeapVear(Date &d);
//data.cpp #include <iostream> #include "data.h" using namespace std; void init(Date &d) { cin>>d.year; cin>>d.month; cin>>d.day; } void print(Date &d) { cout<<"year="<<d.year<<"month="<<d.month<<"day="<<d.day<<endl; } bool isLeapVear(Date &d) { if(d.year%4==0||d.year%100!=0||d.year%400==0) return true; else return false; }
//strut.cpp #include <iostream> #include "data.h" using namespace std; //2017/1/14 c语言风格的封装 数据放在一起,以引用和指针的方式传给行为 int main() { Date d;//此时才会开辟空间 init(d); print(d); if(isLeapVear(d)) { cout<<"d.year"<<"is a leap year"<<endl; }else cout<<"d.year"<<"is not a leap"<<endl; return 1; }
然后再看看c++的class
//data.h #ifndef DATE_H #define DATE_H namespace space { class Date{ public: void init(); void print(); bool isLeapVear(); int getyear(); int getday(); int getmonth(); private: int year; int month; int day; }; } #endif
1 //data.cpp
2
3 #include <iostream>
4 #include "data.h" 5 using namespace std; 6 namespace space 7 { 8 void Date:: init() 9 { 10 cin>>year; 11 cin>>month; 12 cin>>day; 13 } 14 int Date::getyear() 15 { 16 return year; 17 } 18 int Date:: getmonth() 19 { 20 return month; 21 } 22 int Date:: getday() 23 { 24 return day; 25 } 26 bool Date:: isLeapVear() 27 { 28 if(year%4==0||year%100!=0||year%400==0) 29 return true; 30 else 31 return false; 32 } 33 34 void Date:: print() 35 { 36 cout<<"year:"<<year<<"month"<<month<<"day"<<day<<endl; 37 } 38 }
1 //main.cpp
2
3 #include <iostream>
4 #include "data.h" 5 using namespace std; 6 using namespace space; 7 //2017/1/14 8 9 //1 增加了权限控制 相对于c 10 //private: 11 //public: 12 //2 数据和行为在一起,对本类是开放的 对外提供接口 13 14 //声明很实现要分开 15 16 17 //class MM 18 //{ 19 //public: 20 // void init(); 21 //}; 22 //void MM::init();这两个类都有init 所以需要域名 23 int main() 24 { 25 Date d; 26 //d.year = 300;//直接访问不到 默认为私有的 修改为共有 则可以访问 27 d.init(); 28 d.isLeapVear(); 29 d.print(); 30 if(d.isLeapVear()) 31 { 32 cout<<d.getyear()<<"is a leap year"<<endl; 33 }else 34 cout<<d.getyear()<<"is not a leap"<<endl; 35 return 0; 36 }
再不用各种传参。。。。。