运算符重载和友元

重载

函数重载:

在同一个作用域中,可以生命几个功能类似的同名函数,但这些同名函数的形式参数(指参数个数,类型或者顺序)必须不同。参见构造函数定义

运算符重载:

举例如下:

student student::operator+(student &a)

{

student sum;

sum.weight=weight+a.weight;

sum.height=height+a.height;

return sum;}

使用方法:

Student sum;

Student a(40,1.5);

Student b(35,1,0);

Sum=a+b;//method 1

Sum=a.operator+(b);//method 2

友元

友元分为三种:友元函数,友元类,友元成员函数。

非成员函数是无法访问类成员的,为了解决该问题,创建了友元函数

1)创建友元函数首先将友元函数声明放在类声明中。

friend student operator *(double m, const student & s)

2)编写函数定义,因为不是成员函数所以不需要使用限定符student::。另外,也不要在定义中使用friend,定义如下:
student operator*(double m, const student &s)

{

Student result;

result.weight=m*s.weight;

result.height=m*s.height;

return result;

}

类的友元函数是非成员函数,其访问权限与成员函数相同。只有类声明才能决定哪一个函数是友元,友元和类方法可以类比在一起。

友元类:友元类的所有成员函数都是另一个类的友元函数,都可以访问另一个类的隐藏信息。当希望类a可以访问另一个类b的成员时将a声明为b的友元类

Class b

{

friend class a;

}

猜你喜欢

转载自www.cnblogs.com/dongchaoup/p/10385403.html
今日推荐