friend关键字

本文介绍C++中的友元关键字及其用法,包括如何声明友元函数和友元类来访问类的私有成员。同时,通过实例展示了如何使用友元特性重载C++中的输入输出运算符,实现类对象的便捷输出。
C++学习笔记:friend ostream &operator<<(ostream &stream, const Date& dt);

friend关键字

c++中有个friend关键字,它能让被修饰的对象冲破本class的封装特性,从而能够访问本class的私有对象。

简单来讲,就是:

  • 如果你在A类中,申明了函数func()是你的friend,那么func()就可以使用A类的所有成员变量,无论它在什么地方定义的。

  • 如果你在A类中,申明了B类是你的friend,那么B类中的方法就可以访问A类的所有成员变量。

#include<iostream>
using namespace std;

class A {
public:
    A() {
        password = 1111;
        birthday = 808;
    }

    ~A() { }

    friend int func(A a); // 向c++表示,int func(A a)是我的朋友,所以它可以使用我的所有东西。
    friend class B;       // 向c++表示,class B是我的朋友,所以它可以使用我的所有东西。

private:
    int password;
    int birthday;
};

int func(A a) {
    cout << a.password << " and " << a.birthday << endl; //可以访问
    a.password = 1;                                      //甚至可以修改
    cout << a.password << endl;
    return 0;
}

class B {
public:
    B() { }

    ~B() { }
    // 因为在A类中已经声明了B类是它的朋友,所以B类中方法就可以访问A类的私有变量了
    void show(A a) {
        cout << "your account is " << a.account << " and with pass: " << a.password << endl;
    }

private:
};

int main() {

    A a;

    func(a);

    B b;

    b.show(a);

    system("pause");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

运用friend重载 << 或者 >>操作

利用这一点,我们就可以重载<< 或者 >>操作,

#include<iostream>
using namespace std;

class A {
public:
    A() {
        password = 1111;
        account = 808;
    }

    ~A() { }

    friend ostream& operator << (ostream &os , A a);

private:
    int password;
    int account;
};

ostream& operator << (ostream &os , A a) {
    os << "your account is " << a.account << " and with pass: " << a.password << endl;
    return os;
}

int main() {

    A a;

    cout << a;

    system("pause");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

结果:

这里写图片描述
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值