细说C++的友元

2023-06-08,,

为了把C++的友元讲的通俗易懂,我就从这个地球上一种很神奇的生物——女人,说起。众所周知,女生不愿意让别人知道的两个秘密,一个是年龄,另一个就是体重了(虽然已经知道很多年了,但是依然不懂,为什么女生不愿意让别人知道她们的年龄和体重,这很重要吗?)。现在,我们根据这一特性,来创建一个女朋友。由于,女生不想要让别人知道她们的年龄和体重,也就意味着,这两个变量是private变量,这样,外界就不能随意访问了。现在,开始创建这个类:

class Girlfriend{
private:
    int age;
    int weight;
    public:
    Girlfriend ( int age, int weight ){

        this->age = age;
        this->weight = weight;
    }
    int GetAge ( void ){

        return this->age;
    }
    int GetWeight ( void ){
        return this->weight;
    }

};

现在,我们已经有了“女朋友”这个类了。既然我们这些写程序的码畜没有对象,那么我们就基于这个类,来创建一个对象。

Girlfriend Alice;

现在,我们已经有一个对象了,叫Alice。
比如,我们现在其他人想要知道Alice的年龄,体重,看一下,她同意吗?

printf ( "Alice's age is %d\n", Alice.age );
printf ( "Alice's weight is %d]n", Alice.weight );

运行之后,我们发现,

程序报错了。当然会报错,你以为你是谁,想知道她体重就知道她体重,想知道她年龄就知道她年龄,别做梦了,她是不会告诉你的。
但是,难道就真的不能直接得到她的年龄吗?当然不是,她是我创建出来的对象,那么我就是她男朋友,既然是她男朋友,我理应可以直接知道她的年龄和体重。嘿嘿!
所以,现在,来写一个,boyfriend函数。

void boyfriend ( const Grilfriend& girlfriend );

现在,有了这个全局函数,我们就可以访问了吧。来试一下:

很不幸,竟然连自己的男朋友都不可以访问女友的体重和年龄,这也太过分了吧。怎么可以这样呢?可是,仔细一想,天底下男人这么多,你是她男友,那是因为得到了她的同意的,如果她不同意,你怎么可能能够成为她男友,所以,你现在还得通过她的同意。那么怎么做呢?就是用friend。在Girlfriend这个类内声明这个boyfriend这个函数为友元函数。

friend void boyfriend ( const Girlfriend& girlfriend );

在类内声明这个友元函数之后,我们在类外实现就行了。代码如下:

void boyfriend ( const Girlfriend& girlfriend ){
    printf ( "my girlfriend's old is %d\n", girlfriend.age );
    printf ( "my girlfriend's weight is %d\n", girlfriend.weight );
}

在主函数中,我们创建了Alice这个对象并对她进行初始化

Girlfriend Alice( 20, 105 );

现在,我作为男友,要访问我女友Alice的年龄体重,只要,

boyfriend( Alice );

这样以来,就可以了。
现在,让我们看一下,运行结果:

啊,看来作为男友还是有这点权利的。

完整代码如下:

#include <stdio.h>
#include <stdlib.h>

class Girlfriend{
private:
    int weight;
    int age;
public:
    Girlfriend ( int weight, int age ){
        this->weight = weight;
        this->age = age;
    }
    int GetWeight ( void ){
        return this->weight;
    }
    int GetAge ( void ){
        return this->age;
    }
    friend void  boyfriend ( Girlfriend& girlfriend );
};
void boyfriend ( Girlfriend& girlfriend ){

    printf ( "my girlfriend's weight is %d\n", girlfriend.weight );
    printf ( "my girlfriend's age is %d\n", girlfriend.age );
}
int main ( int argc, char** argv ){
    Girlfriend Alice( 105, 20 );
    //printf ( "my girfriend Alice's weight is %d\n", Alice.weight );
    //printf ( "my girfriend Alice's age is %d\n", Alice.age );
    boyfriend( Alice );

    system ( "pause" );
    return 0;
}

PS:这篇文章,我觉得已经写的比较的通俗易懂了,希望看完这篇文章的小伙伴们,各位大佬们,能顺手点个赞,表示支持。谢谢!


欢迎打赏!哈哈哈哈!

《细说C++的友元.doc》

下载本文的Word格式文档,以方便收藏与打印。