C++ Friend class
2014-04-14 23:09
465 查看
Here again, to learn the friend class in C++. And here is a demo for a better understanding.
The demo is mainly to summary the working days till defined date in a year, and using the friend class to realize it.
More, if we don't want to pre-define the class date, we can do like the following, seems a more better way.
The demo is mainly to summary the working days till defined date in a year, and using the friend class to realize it.
/* Author: Charles Pan Date: 4/14/2014 TODO: For the study of friend class in C++ */ #include <iostream> using namespace std; class Date; class CustomDate { private: int da,yr; public: CustomDate(int d = 0,int y =0) {da = d; yr = y;} void Display() const {std::cout<<std::endl<<yr<<da;} friend Date; }; class Date { private: int da,mo,yr; public: Date(int m,int d,int y) { da = d; mo = m; yr = y; } operator CustomDate(); }; Date::operator CustomDate() { ///assume this is the working days of this year. static int dys[]= {23,12,21,22,14,23,12,21,22,14,11,18}; CustomDate cd(0,yr); ///summay the total work days till defined date of this year. ///here, in the class date, we access the private memeber "da" of class CustomDate. Coz friend, so we can. ///This is the kernal part of this code!!! for(int i=0;i<mo;i++) cd.da += dys[i]; cd.da+=da; return cd; } int main() { Date dt(4,13,2014); ///convert date to customdate. CustomDate cd(dt); cd.Display(); char *tt; cin >>tt; return 0; }
More, if we don't want to pre-define the class date, we can do like the following, seems a more better way.
//class Date; //coment this line class CustomDate { private: int da,yr; public: CustomDate(int d = 0,int y =0) {da = d; yr = y;} void Display() const {std::cout<<std::endl<<yr<<da;} friend class Date; //different with friend Date };
相关文章推荐
- C++中friend的使用(friend function and friend class)
- [C++] C++中friend的使用(friend function and friend class)
- C++中friend的使用(friend function and friend class)
- C++ - 类模板(class template)友元(friend) 的 全部六种形式 及 代码
- C++ friend class与namespace冲突引起的思考
- C++中friend的使用(friend function and friend class)
- C++中friend的使用(friend function and friend class)
- C++ - 类模板(class template)友元(friend) 的 全部六种形式 及 代码
- C++ class friend
- 面向对象程序设计-C++ Class & Object & Friend Function & Constructor & Destructor【第五次上课笔记】
- C++中friend的使用(friend function and friend class) .
- C++ - 类模板(class template)友元(friend) 的 全部六种形式 及 代码
- C++ friend function and friend class
- C++::Class Friend
- C++ 关键字:friend
- C++对象模型(四):class成员初始化列表(Member Initialization List)
- C++中的class
- C++继承与Class 内存模型
- 这篇文章记录C++中struct与class的区别
- C和C++中FindClass用法区别