本文主要是介绍C++友元friend,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1普通函数声明友元函数
#include<iostream>
using namespace std;
class Timer
{public:Timer(int,int,int);friend void display(Timer& t);private:int h;int m;int s;
};
Timer::Timer(int a,int b,int c)
{h=a;m=b;s=c;
}
void display(Timer& t)
{cout<<t.h<<endl;cout<<t.m<<endl;cout<<t.s<<endl;
}
int main()
{Timer timer(12,34,56);display(timer);return 0;
}
2成员函数声明友元函数
#include<iostream>
using namespace std;
class Date;
class Time
{public:Time(int,int,int);void display(Date& d);private:int hour;int min;int sec;};
class Date
{public:Date(int,int,int);friend void Time::display(Date& d);private:int year;int mon;int day;
};
Time::Time(int a,int b,int c)
{hour=a;min=b;sec=c;
}
Date::Date(int a,int b,int c)
{year=a;mon=b;day=c;
}
void Time::display(Date& d)
{cout<<d.year<<" "<<d.mon<<d.day<<endl;cout<<hour<<min<<sec<<endl;
}
int main()
{Time t1(11,22,33);Date d1(44,55,66);t1.display(d1);return 0;
}
3友元类
#include<iostream>
using namespace std;
class Date;
class Time
{public:Time(int,int,int);void display(Date& d);private:int hour;int min;int sec;};
class Date
{public:Date(int,int,int);friend class Time;private:int year;int mon;int day;
};
Time::Time(int a,int b,int c)
{hour=a;min=b;sec=c;
}
Date::Date(int a,int b,int c)
{year=a;mon=b;day=c;
}
void Time::display(Date& d)
{cout<<d.year<<" "<<d.mon<<d.day<<endl;cout<<hour<<min<<sec<<endl;
}
int main()
{Time t1(11,22,33);Date d1(44,55,66);t1.display(d1);return 0;
}
这篇关于C++友元friend的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!