类成员函数和类作为朋友
Class Member Functions and Classes as Friends
我写了两个类:第一个类的函数无法访问第二个类的私有成员,即使该函数是第二个类的朋友。 然后我从 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; }
如果错误仍然存在,则可能是您的编译器有问题。
相关文章:
- 为什么即使我声明了朋友类,我也会收到错误"无法访问类中声明的私人成员"
- 访问私人成员而不使用朋友类
- "朋友"成员函数和 GCC 与 Clang
- C 朋友课程和朋友成员功能
- 成员函数作为朋友:利普曼第五本书错了吗?
- C 成员充当朋友
- 我们如何将Ostream函数作为类的成员函数实现,而不是作为朋友函数,以便我可以用作虚拟函数
- 如何将指针用于朋友函数作为成员函数的参数
- 我正在尝试使用朋友功能,但我无法访问第二类的私人数据成员
- 致电另一堂课中的班级的朋友成员失败
- 朋友超载的派生类和基本成员访问的运营商
- 朋友功能无法访问私有成员变量
- 将受保护的结构成员分配给朋友
- 朋友向成员操作员*的模板运营商*声明*
- 当函数应该改变对象的状态时,是选择成员函数还是朋友函数
- 当作为朋友的类具有相同名称的成员变量时会发生什么
- 在没有朋友的情况下测试C++中的私有类成员
- 从另一个类访问类成员,最好使用指针还是朋友
- C++中的向上投射是否允许访问父母的私人成员或朋友
- 使用未命名的命名空间在API中重新定义朋友类并访问私有成员