非成员友元函数、成员友元函数和友元类
1、友元的作用:
(1)友元提供了不同类的成员函数之间、类的成员函数与一般函数之间进行了数据共享的机制;
2、友元的优点和缺点
优点:提高程序的运行效率;
缺点:破坏了类的封装性和数据隐藏性,导致程序的可维护性变差;
3、特点:
(1)友元函数是可以直接访问类的私有成员的非成员函数;
(2)友元函数是定义在类外的普通函数,它不属于任何类;
(3) 一个函数可以是多个类的友元函数;
4、使用场景
(1)运算符重载的某些情况会使用友元;
(2) 两个类要共享数据的时候;
// OperatorOverload.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 #include "pch.h" #include <iostream> using namespace std; class Time { private: int hours; int minutes; public: Time(); //默认构造函数 Time(int h, int m); //重载构造函数 void addHr(int h); void AddMin(int m); void reset(int h = 0, int m = 0);
//重载运算符(二元)(1)至少有一个数据对象是自定义数据类型;(2)左边必须为自定义的数据类型
Time operator+(const Time &t) const; //+运算符重载,Time T1, T2; T1 + T2会编译为 T1.operator+(T2); Time operator-(const Time &t) const; //-运算符重载, Time T1, T2; T1 - T2会编译为T Time operator*(double n) const; friend Time operator*(double m, const Time &t); //友元函数(类的非成员函数) friend ostream & operator<<(ostream &os, const Time &t); }; Time::Time() { hours = minutes = 0; } Time::Time(int h, int m) { hours = h; minutes = m; } void Time::AddMin(int m) { minutes += m; hours += minutes / 60; minutes %= 60; } void Time::addHr(int h) { hours += h; } void Time::reset(int h, int m) { hours = h; minutes = m; } /*重载运算符+ 1、也可以使用如下友元函数原型:friend Time Time::operator+(const Time &t1, cosnt Time &t2); 2、Time t1,t2; (1)运算符重载左侧的操作数为调用对象 (2)两个Time对象相加:t1 + t2,转换为下面两个的任意一个(两者只能选择其中一个): (3)t1.operator+(t2); //member function (4)operator+(t1,t2); //nomember function */ Time Time::operator+(const Time &t) const { Time sum; sum.minutes = minutes + t.minutes; sum.hours = hours + t.hours + sum.minutes/60; sum.minutes %= 60; return sum; } Time Time::operator-(const Time &t) const { Time diff; int tot1, tot2; tot1 = t.minutes + 60 * t.hours; tot2 = minutes + 60 * hours; diff.minutes = (tot2 - tot1) % 60; diff.hours = (tot2 - tot1) / 60; return diff; } Time Time::operator*(double mult) const { Time result; long totalMinutes = (minutes + 60 * hours) * mult; result.hours = totalMinutes / 60; result.minutes = totalMinutes % 60; return result; } ostream & operator<< (ostream & os, const Time &t) { os << t.hours << "hours" << t.minutes << "minutes"; return os; } Time operator*(double m, const Time &t) { return t * m; } int main() { }