代码改变世界

c++中的第三次作业

2019-09-26 17:23  myself914  阅读(146)  评论(0编辑  收藏  举报

c++中的第三次作业
类的友元
首先看一个例子在:类b中内嵌了类a的对象,那么可不可通过b的成员函数访问a的私有成员:

#include<iostream>
using namespace std;
class A
{
public:
    void setX()
    {
        cout<<x<<endl;
    }
    int getX()
    {
        return x;
    }
private:
    int x;
};
class B
{
public:
    void set(int i);
    void display();
    friend class B;
private:
    A a;
};
void B::set(int i)
{
    a.x=i;
}
void B::display()
{
    cout<<a.x<<endl;
}
int main()
{
    B b;
    b.set(10);
    b.display();
    return 0;
}

编译时却显示:

这样做是不能成功的,由此引入了友元关系:一个类主动声明哪些其他类或函数是它的朋友,进而给他们提供对本类的访问特许。友元关系提供了不同类或对象的成员函数之间、类的成员函数与一般函数之间进行数据共享的机制。
那么将上面那个例子用友元类改写一下:

#include<iostream>
using namespace std;
class A
{
public:
    void setX()
    {
        cout<<x<<endl;
    }
    int getX()
    {
        return x;
    }
    friend class B;//加入友元关系
private:
    int x;
};
class B
{
public:
    void set(int i);
    void display();
private:
    A a;
};
void B::set(int i)
{
    a.x=i;
}
void B::display()
{
    cout<<a.x<<endl;
}
int main()
{
    B b;
    b.set(10);
    b.display();
    return 0;

}

此时的编译成功了,结果是:

友元函数
在友元函数的函数体中可以通过对象名访问类的私有和保护成员
例子:使用友元函数计算两点之间的距离

#include<iostream>
using namespace std;
class Point
{
public:
    Point(int x=0,int y=0):x(x),y(y){}
    int getX()
    {
        return x;
    }
    int getY()
    {
        return y;
    }
    friend float dist(Point &p1,Point &p2);
private:
    int x,y;
};
float dist(Point &p1,Point &p2)
{
    double x=p1.x-p2.x;//通过对象名直接访问私有成员
    double y=p1.y-p2.y;
    return static_cast<float>(sqrt(x*x+y*y));
}
int main()
    {
        Point myp1(1,1),myp2(4,5);
        cout<<"The distance is:"<<endl;
        cout<<dist(myp1,myp2)<<endl;
        return 0;
    }

运行结果是:

可以看到在友元函数中通过对象名直接访问了Point类中的私有数据成员x和y。
注意:
友元关系是不能传递的;友元关系是单向的;友元关系是不能被继承的。