⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 例9.13.txt

📁 是关于谭浩强老师的C++程序设计课程的程序源代码以及课件
💻 TXT
字号:
例9.13 友元成员函数的简单应用。
在本例中除了介绍有关友元成员函数的简单应用外,还将用到类的提前引用声明,请读者注意。
#include <iostream>
using namespace std;
class Date;                 //对Date类的提前引用声明
class Time                  //定义Time类
{public:
Time(int,int,int);
void display(Date &);    //display是成员函数,形参是Date类对象的引用
 private:
int hour;
int minute;
int sec;
};

class Date                               //声明Date类
{public:
Date(int,int,int);
friend void Time∷display(Date &);    //声明Time中的display函数为友元成员函数
 private:
int month;
int day;
int year;
};

Time∷Time(int h,int m,int s)    //类Time的构造函数
{hour=h;
minute=m;
sec=s;
}

void Time∷display(Date &d)       //display的作用是输出年、月、日和时、分、秒
{cout<<d.month<<″/″<<d.day<<″/″<<d.year<<endl;   //引用Date类对象中的私有数据
cout<<hour<<″:″<<minute<<″:″<<sec<<endl;        //引用本类对象中的私有数据
}

Date∷Date(int m,int d,int y)          //类Date的构造函数
{month=m;
day=d;
year=y;
}

int main( )
{Time t1(10,13,56);             //定义Time类对象t1
Date d1(12,25,2004);           //定义Date类对象d1
t1.display(d1);                //调用t1中的display函数,实参是Date类对象d1
return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -