友元

2021-08-19  本文已影响0人  李永开

一.友元

友元函数,目的是访问类中的私有成员属性

二.全局函数做友元函数

//
//  main.c
//  cdemo
//
//  Created by liyongkai on 2021/6/6.
//

#include <iostream>
using namespace std;

class Person{
//加上这句话,下面就不会报  't' is a private member of 'Person'
friend void test(Person *person);
    
public:
    int p = 10;
private:
    int t = 20;
};

//这是一个全局函数
void test(Person *person) {
    cout << person->p << endl;
    cout << person->t << endl;//'t' is a private member of 'Person'
}

int main(int argc, const char * argv[]) {
    
    test(new Person);
    
    return 0;
}

三.整个类作为友元类

//
//  main.c
//  cdemo
//
//  Created by liyongkai on 2021/6/6.
//

#include <iostream>
using namespace std;

class Person{
friend class Dog;//友元类
    
public:
    int p = 10;
private:
    int t = 20;
};

class Dog{
public:
    void showPerson(Person *person){
        cout << person->t << endl;//'t' is a private member of 'Person'
    };
};


int main(int argc, const char * argv[]) {
    
    Dog().showPerson(new Person);
    
    return 0;
}

四.其他类的成员函数也可以作为友元类

上一篇 下一篇

猜你喜欢

热点阅读