友元类互相指向对方
如何创建两个类,它们具有指向彼此类类型的成员指针,并且可以完全访问彼此的数据?换句话说,我需要两个这样的类:
class A
{
protected:
B *p;
};
class B
{
protected:
A *p;
};
我遇到了麻烦,因为我不符合 C++ 约定,显然,类 A 不能声明类 B,因为 B 是稍后在代码中声明的。
感谢您的帮助
How can I create two classes that have member pointers to each other's class type, with full access to each other's data? In other words, I need two classes like this:
class A
{
protected:
B *p;
};
class B
{
protected:
A *p;
};
I'm having trouble with it because I'm not up to par with C++ conventions, and obviously, class A can't declare a class B because B is declared later in the code.
Thanks for the help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您应该使用前向类声明。
You should use forward class declaration.
请注意,实际使用 B 成员的任何 A 成员函数都必须在 B 定义之后定义,例如:
Note that any member functions of A which actually use the members of B will have to be defined after the definition of B, for example:
您必须使用前向声明,例如:
you must use forward declaration like:
如果你想声明友谊,你需要一个前置声明:
If you want to declare friendship, you need a forward declaration:
您可以通过在 A 类之上执行
class B;
来使用前向声明You could use a forward declaration by doing
class B;
above class A简单使用:
B 级;
使用B类;意味着前向声明,这基本上告诉编译器:“B 类存在于某处”。
simple use:
class B;
Using class B; means a forward declaration and this basically tells the compiler: "class B exists somewhere".