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

C++ 友元函数、友元类、友元成员函数

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

C++ 友元函数、友元类、友元成员函数

1.友元函数
可以访问不受public protected private影响。

func.h

#ifndef __FUNC__
#define __FUNC__

#include
#include
using namespace std;
#include "test.h"

class Test;

void testFuncFriend(const Test &tempmen);

#endif // !__FUNC__

func.cpp

#include
#include
#include "func.h"
using namespace std;

void testFuncFriend(const Test &temp) {
    cout << "testFuncFriend" << endl;
    temp.testFunc();
}

test.h

#ifndef __TEST__
#define __TEST__
#include
#include
#include "func.h"
using namespace std;
class Test
{
public:
    Test();
private:
    void testFunc() const{
        cout << "test" << endl;
    }
    friend void testFuncFriend(const Test &temp);
};
#endif // !__Test__

 test.cpp

#include
#include
#include "test.h"
using namespace std;

Test::Test() {
    cout << "执行了Test::Test()构造函数" << endl;
}

main.cpp

#include
#include
#include "func.h"
#include "test.h"
using namespace std;

int main()
{
    Test test;
    testFuncFriend(test);
    return 0;
}

通过在Test中添加friend void testFuncFriend(const Test &temp);就可以在func的testFuncFriend中访问Test中的private(testFunc)方法。

2.友元类与友元成员函数

A.cpp

#include
#include
using namespace std;
#include "A.h"

A.h

#ifndef __A__
#define __A__

#include "C.h"
class A
{
    friend void C::cCallA(int x,A &a);//此函数内才能访问A中的成员变量和成员函数
    //friend class C;//添加之后 C可以访问A所有的成员变量和成员函数
private:
    int data;
};
#endif

c.cpp

#include
#include
using namespace std;

#include "A.h"
#include "C.h"

void C::cCallA(int x,A &a) {
    a.data = x;
    cout << a.data << endl;
    cout << "cCallA" << endl;
}

c.h

#ifndef __C__
#define __C__

#include
#include
using namespace std;
class A;
class C 
{
public:
    void cCallA(int x,A &a);
};

#endif // !__C__

main.cpp

#include
#include
#include "func.h"
#include "A.h"
#include "C.h"
#include "test.h"
using namespace std;


int main()
{

    A a;
    C c;
    c.cCallA(10,a);

    Test test;
    testFuncFriend(test);

    return 0;
}

结果为:

10

cCallA

执行了Test::Test()构造函数

testFuncFriend

test
通过在A中添加friend void C::cCallA(int x,A &a);就可以访问A中的私有变量。

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

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

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