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

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

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

这是一个演示程序

#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
本文链接:https://www.f2er.com/3108595.html

大家都在问