细说C++的友元

为了把C++的友元讲的通俗易懂,我就从这个地球上一种很神奇的生物——女人,提及。众所周知,女生不肯意让别人知道的两个秘密,一个是年龄,另外一个就是体重了(虽然已经知道不少年了,可是依然不懂,为何女生不肯意让别人知道她们的年龄和体重,这很重要吗?)。如今,咱们根据这一特性,来建立一个女友类。因为,女生不想要让别人知道她们的年龄和体重,也就意味着,这两个变量是private变量,这样,外界就不能随意访问了。如今,开始建立这个类:ide

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的年龄,体重,看一下,她赞成吗?this

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

运行以后,咱们发现,
细说C++的友元
程序报错了。固然会报错,你觉得你是谁,想知道她体重就知道她体重,想知道她年龄就知道她年龄,别作梦了,她是不会告诉你的。
可是,难道就真的不能直接获得她的年龄吗?固然不是,她是我建立出来的对象,那么我就是她男友,既然是她男友,我理应能够直接知道她的年龄和体重。嘿嘿!
因此,如今,来写一个,boyfriend函数。3d

void boyfriend ( const Grilfriend& girlfriend );

如今,有了这个全局函数,咱们就能够访问了吧。来试一下:
细说C++的友元
很不幸,居然连本身的男友都不能够访问女朋友的体重和年龄,这也太过度了吧。怎么能够这样呢?但是,仔细一想,天底下男人这么多,你是她男朋友,那是由于获得了她的赞成的,若是她不一样意,你怎么可能可以成为她男朋友,因此,你如今还得经过她的赞成。那么怎么作呢?就是用friend。在Girlfriend这个类内声明这个boyfriend这个函数为友元函数。code

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这个对象并对她进行初始化blog

Girlfriend Alice( 20, 105 );

如今,我做为男朋友,要访问我女朋友Alice的年龄体重,只要,it

boyfriend( Alice );

这样以来,就能够了。
如今,让咱们看一下,运行结果:
细说C++的友元
啊,看来做为男朋友仍是有这点权利的。io

完整代码以下:class

#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++的友元

相关文章
相关标签/搜索