C++友元函数参考
我有这种情况(两个类有两个不同的头文件):
bh
#include "a.h"
class B {
friend void B* A::create(void);
private:
int x;
};
ah
#include "b.h"
class A {
public:
void B* create(void);
...
};
基本上 A 类创建“B”对象。我想授予创建函数 create() 访问权限来修改类 B 的私有成员“x”。我想在 C# 中模拟“internal”关键字,但要在更精细的级别上进行。
我遇到的问题是我最终得到了一个循环标题引用。 bh 想要跟随 ah,但是 ah 想要跟随 bh 这样做的正确方法是什么?我需要求助于 void* ptr 吗?由于我只创建一种类型的对象,因此我认为我不需要工厂模式。希望我错过了一些简单的事情。
I have this situation (two classes with two different header files):
b.h
#include "a.h"
class B {
friend void B* A::create(void);
private:
int x;
};
a.h
#include "b.h"
class A {
public:
void B* create(void);
...
};
basically class A creates "B" objects. I want to give the creation function create() access to modify the private member 'x' of class B. I want to simulate the 'internal' keyword in C#, but at a more granular level.
The problem I have is that I end up with a circular header reference. b.h wants to come after a.h, but a.h wants to come after b.h. What is the proper way of doing this? Do I need to resort to void* ptrs? Since I only create one type of object, i don't think I need the factory pattern. Hopefully I'm missing something simple.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要的是“前瞻性声明”。基本上,您不会将类的标头包含在其他类的标头中(除非您想使用组合,否则您必须这样做)。在您的情况下,它看起来像这样:
在 Ah 中反过来,
您可能需要在 B.cpp 中包含 Ah (以及相反的方式)才能真正取消引用那些访问字段的指针,但是您的循环标头包含问题现已消失。
What you need is a "forward declaration". Basically you don't include the classes' headers in other classes' headers (unless you want to use composition, then you have to). In your case, it'd look like this:
And the other way round in A.h.
You'd probably need to include A.h in B.cpp (and the other way round) to be able to actually dereference those pointers to access fields, but your problem with circular header inclusion is now gone.