C++中友元的知识点有哪些

发布时间:2021-11-24 11:45:42 作者:iii
来源:亿速云 阅读:145

这篇文章主要讲解了“C++中友元的知识点有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++中友元的知识点有哪些”吧!

一、友元的概念:

1、什么是友元?

C++中友元的知识点有哪些 

2、友元的用法:

3、友元的语法:

在类中使用friend 关键字对函数或者类进行声明:

class Test
{
     double x;
     double y;

     friend void func(Test& t);

};

void func(Test& t)
{


}
 

注意:func() 全局函数是 Test 类的友元,func() 可以访问Test 类的所有成员,但是 func() 不是 Test 的成员函数。

示例代码:

#include <stdio.h>
#include <math.h>

class Test
{
    double x;
    double y;
public:
    Test(double x,double y)
    {
       this->x=x;
       this->y=y;
    }
    double getX()
    {
       return x;
    }
    double getY()
    {

       return y;
     }
    friend double func(Test& t1,Test& t2);

};

double func(Test& t1,Test& t2)
{
       double ret =0;
       ret = (t2.y-t1.y)*(t2.y-t1.y)+(t2.x-t1.x)*(t2.x-t1.x);

        ret = sqrt(ret);

     return ret;

}
int main()
{
    Test t1(1,2);
    Test t2(10,20);

    printf("t1(%f,%f)\n",t1.getX(),t1.getY());
    printf("t2(%f,%f)\n",t2.getX(),t2.getY());
    printf("(t1,t2)=%f\n",func(t1,t2));

    
    return 0;
}

 

输出结果:

root@txp-virtual-machine:/home/txp/add# g++ test.cpp
root@txp-virtual-machine:/home/txp/add# ./a.out
t1(1.000000,2.000000)
t2(10.000000,20.000000)
(t1,t2)=20.124612

 

4、友元的尴尬:

5、注意事项:

C++中友元的知识点有哪些  

代码测试:

#include <stdio.h>

class ClassC
{
    const char* n;
public:
    ClassC(const char* n)
    {
        this->n = n;
    }
    
    friend class ClassB;
};

class ClassB
{
    const char* n;
public:
    ClassB(const char* n)
    {
        this->n = n;
    }
    
    void getClassCName(ClassC& c)
    {
        printf("c.n = %s\n", c.n);
    }
    
    friend class ClassA;
};

class ClassA
{
    const char* n;
public:
    ClassA(const char* n)
    {
        this->n = n;
    }
    
    void getClassBName(ClassB& b)
    {
        printf("b.n = %s\n", b.n);
    }
    /*
    void getClassCName(ClassC& c)
    {
        printf("c.n = %s\n", c.n);
    }
    */
};

int main()
{
    ClassA A("A");
    ClassB B("B");
    ClassC C("C");
    
    A.getClassBName(B);
    B.getClassCName(C);
    
    return 0;
}

 

输出结果:

root@txp-virtual-machine:/home/txp/add# ./a.out
b.n = B
c.n = C

 

如果把上面屏蔽的那部分代码打开,编译就会报错(因为友元没有传递性哦):

root@txp-virtual-machine:/home/txp/add# g++ test.cpp
test.cpp: In member function ‘void ClassA::getClassCName(ClassC&)’:
test.cpp:5:17: error: ‘const char* ClassC::n’ is private
     const char* n;
                 ^
test.cpp:48:32: error: within this context
         printf("c.n = %s\n", c.n);
                                ^
 

6、小结:

感谢各位的阅读,以上就是“C++中友元的知识点有哪些”的内容了,经过本文的学习后,相信大家对C++中友元的知识点有哪些这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 细说C++的友元
  2. C++中友元的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:windows server 2003文件服务器权限如何设置

下一篇:C++中为什么不要使用抛异常声明

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》