目标 C 中的朋友类 [英] Friend class in Objective C
问题描述
我正在将 cpp 代码移植到 Objective C.
I am porting cpp code into Objective C.
在cpp
中,我们可以将一个类作为friend class
添加到另一个类中,并使用其所有公共函数和变量.
In cpp
we can add a class as friend class
to another class and use all its public functions and variables.
我知道Objective C 不支持友元类
概念.
我如何在Objective C中将一个类作为另一个类的朋友
How do i make a class as a friend to another class in Objective C
推荐答案
如果您有两个紧耦合的类,那么您可以使用一些简单的技巧来公开一个更简单的公共接口.例如,
If you have two tightly-coupled classes, then you can use some simple tricks to expose a simpler public interface. For example,
在 Banana.h
中:
@interface Banana : NSObject
- (BOOL)isPeeled;
@end
在 Monkey.h
中:
@interface Monkey : NSObject
- (void)eat:(Banana *)aBanana;
@end
在 BananaPrivate.h
中:
@interface Banana (PrivateMethods)
- (void)peel;
@end
然后你的 Monkey.m
文件可以导入 BananaPrivate.h
来获取私有函数.如果您正在编写框架,则不要在框架标头中包含 BananaPrivate.h
.
Then your Monkey.m
file can import BananaPrivate.h
to get the private functions. If you're writing a framework, then you don't include BananaPrivate.h
in your framework headers.
这与在 C 中完成封装的方式相同.在我看来,它比 C++
中的 friend
关键字破坏性要小得多,但这超出了本答案的范围解释原因.
This is the same way encapsulation is done in C. In my opinion it's significantly less broken than the friend
keyword in C++
, but it's beyond the scope of this answer to explain why.
如果您将 Banana 实现为类集群,您也可以通过这种方式公开私有成员变量,但这有点疯狂,我不推荐这样做.如果您需要类之间更紧密的耦合,您可能希望在该部分代码中使用 C 习语.
You can also expose private member variables this way if you implement Banana as a class cluster, but that's kind of insane and I don't recommend it. If you need even closer coupling between classes you might want to use C idioms for that part of the code.
这篇关于目标 C 中的朋友类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!