如何为具有多个成员函数的类中的特定成员函数提供朋友函数,以便指定的成员函数

问题描述 投票:0回答:1

如何为具有多个成员函数的类中的特定成员函数提供朋友函数,以使指定的成员函数只能访问另一个类的私有数据,而其他成员函数则不能。

c++
1个回答
0
投票

这里是示范节目

#include <iostream>

struct A
{
    void f() const;
};

class B
{
public:
    B( int i = 0 ) : i( i ) {}

    friend void A::f() const;

private:
    int i;
};

void A::f() const
{
    B b( 10 );

    std::cout << "b.i = " << b.i << '\n';
}

int main() 
{
    A().f();

    return 0;
}

程序输出为

b.i = 10
© www.soinside.com 2019 - 2024. All rights reserved.