栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++友元成员函数

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++友元成员函数

友元成员函数

       在前面的例子中,我们定义了一个普通的函数,然后,在定义一个类的时候,把这个函数声明为该类的“朋友”,可以让该函数访问类中的成员变量。

       同样,我们也在定义一个类的时候,把另一个类的成员函数声明为该类的朋友,让它可以访问自己的成员变量。

       所以,firent 函数不仅可以定义一个普通函数(非成员函数),而且,可以是另一个类中的成员函数。下面举例介绍友元成员函数的使用。

       在这个例子中,除了介绍有关友元成员函数的简单应用外,还将用到类的“提前引用声明”。就是说,一个类在使用之前,没有被定义,而是放在后面定义,那么,我们可以在使用之前先声明它。有如下的类定义:

class student;//提前声明student类;

class my_print//定义 my_print 类;

{

public:

    void print(student& s); //声明函数;

};

class student{

private: //定义私有类型成员变量

    char name[32]; //姓名

    char addr[32]; //家庭地址

    long long number; //电话号码

public: //以下部分是公有部分

    student(char* pn, char* pa, long long n)

    {

        strcpy(name, pn);

        strcpy(addr, pa);

        number = n;

    }

    friend void my_print::print(student& s);//声明友元函数;

};

       可以看到,定义了my_print类和student类。其中,在my_print类中引用student类。而且,student类在最后面定义。

       那么,就在my_print类之前,编写如下的语句:

class student;//提前声明student类;

       表示提前声明student类,那么,就可以在my_print类中引用student类。完整的测试代码如下:

 

       程序编译结果如下:

wkf@ubuntu:~/c++$ g++ test.cpp -o exe

test.cpp: In member function ‘void my_print::print(student&)’:

test.cpp:14: error: invalid use of incomplete type ‘struct student’

test.cpp:6: error: forward declaration of ‘struct student’

test.cpp:15: error: invalid use of incomplete type ‘struct student’

test.cpp:6: error: forward declaration of ‘struct student’

test.cpp:16: error: invalid use of incomplete type ‘struct student’

test.cpp:6: error: forward declaration of ‘struct student’

       可以看到,在my_print::print()函数中,引用student类型的数据异常。为什么会出现这个问题?

       因为,在my_print::print()函数中,引用student类的时候,这个student类还没有定义。我们只是在my_print类之前提前声明了student类。并没有定义student类,所以,编译器在my_print::print()函数中,无法访问s.name, s.addr等成员变量。

       所以,我们可以把my_print::print()函数放在student类定义的后面。表示定义了student类之后,再定义my_print::print()函数,此时,编译器才知道s.name, s.addr成员变量是合法的定义。完整的测试代码如下:

 

       程序运行结果如下:

 

       可以看到,my_print::print()函数能够正确引用了student类中定义的private私有成员。这是因为,在student类中,声明my_print类的print()函数是友元类型,如下:

class student{

...

    friend void my_print::print(student& s);//声明友元函数;

};

       所以,student类中的私有成员,就可以在my_print类的print()函数中被访问。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/920934.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号