本文共 1877 字,大约阅读时间需要 6 分钟。
朋友函数需要在类中任意位置进行声明,与普通函数不同的是要加上friend关键字,并在类外进行实现。朋友函数并非类的成员函数,因此可以访问该类的私有成员。
class Complex {public: Complex(int real = 0, int imag = 0) : m_real(real), m_imag(imag) {} ~Complex() {} Complex operator+(int a) { return Complex(m_real + a, m_imag); }private: int m_real; int m_imag;};class ComplexFriend {public: ComplexFriend(int real, int imag) : m_real(real), m_imag(imag) {} ~ComplexFriend() {}private: int m_real; int m_imag;};friend Complex operator+(int a, const Complex& c) { return Complex(a + c.m_real, c.m_imag);}friend Complex operator+(const Complex& c1, const Complex& c2) { return Complex(c1.m_real + c2.m_real, c1.m_imag + c2.m_imag);}void main() { Complex c, c1(1, 3); c = c1 + 10; c = 10 + c1; c = c1 + c2;}
朋友类的所有成员函数都可以是另一个类的朋友函数,并可以访问另一个类的非公有成员。
// 声明Time类为朋友类,Date类可以访问Time类的私有成员class Date {public: Date(int year = 1900, int month = 1, int day = 1) : _year(year), _month(month), _day(day), _t(9, 30, 45) {} void SetTimeOfDate(int hour, int minute, int second) { _t._hour = hour; _t._minute = minute; _t._second = second; }private: int _year; int _month; int _day; Time _t;};friend class Time;
class Time {public: Time(int hour, int minute, int second) : _hour(hour), _minute(minute), _second(second) {}private: int _hour; int _minute; int _second;};friend class Date;
void main() { Time t1(11, 2, 3); Date d1(2020, 3, 15); Date d2 = d1; d1.SetTimeOfDate(1, 10, 11);}
朋友函数和朋友类为C++提供了灵活的访问控制机制,可以实现类间的非继承式的私有成员访问。然而,朋友关系具有单向性和不传递性,需要谨慎操作。
转载地址:http://rsulz.baihongyu.com/