课程设计__友元
///友元 ///友元有利于数据共享,但是破坏了类的封装性 #include <iostream> using namespace std; class Time { public: Time (int h=10,int m=10,int s=10):hour(h),minute(m),sec(s) {} ///将普通函数放到类中,普通函数可以访问私有成员 friend void display(Time &t); private: int hour; int minute; int sec; }; void display(Time &t) { cout<<t.hour<<" "<<t.minute<<" "<<t.sec<<endl; } int main() { Time t(12,13,14); display(t); return 0; }
///友元 ///友元有利于数据共享,但是破坏了类的封装性 #include <iostream> using namespace std; class Date; ///对Date类提前声明 class Time { public: Time (int h,int m,int s):hour(h),minute(m),sec(s) {}; void display(Date &d); private: int hour; int minute; int sec; }; class Date { public: Date(int m,int d,int y):month(m),day(d),year(y) {} ///声明Time中display函数为本类的友元成员函数,可以访问本类的私有成员 friend void Time::display(Date &d); private: int month; int day; int year; }; void Time::display(Date &d) { cout<<d.month<<" "<<d.day<<" "<<d.year<<endl; cout<<hour<<" "<<minute<<" "<<sec<<endl; } int main() { Time t(10,13,56); Date d(12,25,2016); t.display(d); return 0; }