类成员函数和类作为朋友

Class Member Functions and Classes as Friends

本文关键字:朋友 成员 函数      更新时间:2023-10-16

我写了两个类:第一个类的函数无法访问第二个类的私有成员,即使该函数是第二个类的朋友。 然后我从 msdn.microsoft.com 中找到了这个例子,但仍然有一个错误: cannot access private member declared in class B

以下是来自 MSDN 的代码:

class B;
class A {
public:
    int Func1(B& b);
private:
    int Func2(B& b);
};
class B {
private:
    int _b;
    // A::Func1 is a friend function to class B
    // so A::Func1 has access to all members of B
    friend int A::Func1(B&);
};
int A::Func1(B& b) { return b._b; }//the same error as the one below is here
int A::Func2(B& b) { return b._b; }  

当我class A本身写为B的朋友时,没有错误,但我只想拥有我想成为 B 类朋友的功能,而不是整个class A

是我的编译器错误还是此代码错误?

我只是在顶部为class B添加了一个declaration(称为class的前向声明(,然后它就可以编译了。您需要先声明class B,然后再将其用作class A member functions中的parameter

这是代码 ->

#include<iostream>
class B;
class A {
public:
    int Func1(B& b);
private:
    int Func2(B& b);
};
class B {
private:
    int _b;

    // A::Func1 is a friend function to class B
    // so A::Func1 has access to all members of B
    friend int A::Func1(B&);
};
int A::Func1(B& b) { return b._b; }//the same error as the one below    is here
//int A::Func2(B& b) { return b._b; } 
int main(void){ return 0; }

如果错误仍然存在,则可能是您的编译器有问题。