C++的友元

友元:
     友元包括友元函数和友元类
     如果将函数A(非成员函数)声明为类C的友元函数,那么函数A就能直接访问类C对象的所有成员.
     如果将类A声明为类C的友元类,那么类A的所有成员函数都能直接访问类C对象的所有成员.
     友元破坏了面向对象的封装性,但在某些频繁访问成员变量的地方可以提高性能.

 class Point {
         friend Point add(const Point &,const Point &);
         friend class Math;
         int m_x;
         int m_y;
         public:
         int getX() const {return this->m_x;};
         int getY() const {return this->m_y;};
         Point(int x,int y):m_x(x),m_y(y){}
     };
     
     
     class Math {
     public:
         Point sub(const Point &point1,const Point &point2){
         return Point(point1.getX() - point2.getX(),point1.getY() - point2.getY());
         或者变为友元可以写为:
         return Point(point1.m_x - point2.m_x,point1.m_y - point2.m_y);
         }
     }
     
     Point add(const Point &point1,const Point &point2){
         return Point(point1.getX() + point2.getX(),point1.getY() + point2.getY());
         或者变为友元可以写为:
         return Point(point1.m_x - point2.m_x,point1.m_y - point2.m_y);
     }
     
     
     int main() {
         Point point1(10,20);
         Point point2(20,30);
     
         Point point = add(point1,point2);
     
         cout << << endl;
         getchar();
         return 0;
     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值