C++ 友元函数

在声明中,可以放在该类中private,public,protect中的任意部分。
可以将顶层函数声明为friend,还可以将一个函数声明为另一个类的friend,也可以将类声明为另一个类的friend,以下代码案例分析(类的friend)!

#include <iostream>
using namespace std;

class A{
private:
    int a;
    friend class B;
};
class B{
private:
    int b;
    public:void f(){A a;a.a=10;b=20;cout<<"a.a+b="<<a.a+b<<endl;};
};

int main()
{
    B b;
    b.f();
    return 0;
}
  • friend的关系是单向的,不是双向的,如果声明了A是B的friend,不等于B是A的friend.
  • friend的关系不能传递。
  • friend函数不是类的成员函数,却可以访问该类的私有和保护成员,从严格意义上来说,这不符合面向对象原则
  • 因此friend函数的使用时存在争议的,且容易被勿用。

以下举个操作符重载和friend一起使用案例实现复数的+&-,看下面这段代码。

#include <iostream>
using namespace std;
//用friend和运算符重载实现复数的加减运算。
//class Complex
class Complex
{
private:
        float Real,Image;
public:
        //构造函数
        Complex(float r=0,float i=0)

        {Real=r;Image=i;};
        //成员函数show
        void Show(int i)
        {cout<<"c"<<i<<"="<<Real<<"+"<<Image<<"i"<<endl;}
            //friend的声明
            friend Complex operator+(Complex &,Complex &);
            friend Complex operator-(Complex &,Complex &);
            friend Complex operator+(Complex &,float);

};
//函数的定义和操作符的重载
Complex operator+(Complex &c1,Complex &c2)
{
    Complex t;
    t.Real=c1.Real+c2.Real;
    t.Image=c1.Image+c2.Image;
    return t;
}

Complex operator-(Complex &c1,Complex &c2)
{
    Complex t;
    t.Real=c1.Real-c2.Real;
    t.Image=c1.Image-c2.Image;
    return t;
}

int main(void)
{
   //创建对象 并且初始化
    Complex c1(25,50),c2(110,200),c3,c4;

    c1.Show(1);
    c2.Show(2);

    c3=c1+c2;
    c3.Show(3);

    c4=c2-c1;
    c4.Show(4);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39818571/article/details/78441724