友元解析

本文介绍了C++中友元函数的基本概念及其使用方法。通过示例代码展示了如何利用友元函数访问类的私有成员,并解释了友元函数的作用及定义方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不废话,先上一段代码:

#include <iostream>

class Person{
private:
    int age;
public:
    Person(int age){
        this->age = age;
    }
};

void printAge(Person const &person){
    std::cout << person.age << std::endl;
}

int main(){
    Person alice = Person(24);
    printAge(alice);    //ERROR
    return 0;
}

很明显,由于age是private的变量,所以外部的printAge无法访问,如何访问呢?再看看下面一段代码:

#include <iostream>

class Person{
private:
    int age;
    friend  void printAge(Person const &person);    //New line.
public:
    Person(int age){
        this->age = age;
    }
};

void printAge(Person const &person){
    std::cout << person.age << std::endl;
}

int main(){
    Person alice = Person(24);
    printAge(alice);        //Correct
    return 0;
}

友元函数总结:

友元函数是可以访问private变量的非成员函数。友元函数的定义在全局域,不属于任何类(所以没有this指针),不过需要在作用类中加friend声明(声明可以放在private,也可以放在public)。

一个函数可以同时成为多个类的友元函数(只要在各个类中都有friend声明即可)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值