c++中友元类的使用

来源:互联网 发布:高斯图像金字塔算法 编辑:程序博客网 时间:2024/05/18 01:30
#include <iostream>using namespace std;class Date;//因为在Time中要用Date类,但是还没有定义,所以先声明class Time{private:int hour;int min;int sec;public:Time(int h, int m, int s):hour(h), min(m), sec(s){}void display_time(Date t);};class Date{private:int year;int month;int day;public:Date(int y, int m, int d):year(y), month(m), day(d){}friend class Time;//定义友元类,必须要用class关键词,不能直接friend Time};void Time::display_time(Date t)//传递date类的对象t,并且使用其参数{cout << "Date: " << t.year << "-" << t.month << "-" << t.day << endl;cout << "Time: " << hour << ":" << min << ":" << sec << endl;t.year += 5;//可以对Date类中的私有成员数据进行修改puts("");cout << "Date: " << t.year << "-" << t.month << "-" << t.day << endl;cout << "Time: " << hour << ":" << min << ":" << sec << endl;}int main(int argc, char const *argv[]){Time t1(12, 23, 34);Date d1(2013, 12, 16);t1.display_time(d1);//将对象d1传递给display函数return 0;}

0 0