派生类共享方法

发布于 2024-09-30 15:03:29 字数 246 浏览 1 评论 0原文

我有一个 2 个派生类使用的函数,但第三个派生类没有,即使 3 个派生类之一不使用它,将其保留在基类中是否有意义?

我能想到的禁止第三类的唯一方法是基本上创建一个派生自基类的中间类,然后使用公共函数的两个类派生自第二类。

是否可以阻止第三类使用该函数,同时让应该使用它的两个类使用它?

这似乎太过分了,我的意思是只要我不“尝试”从第三类调用该函数,它就不应该成为问题,我只是感兴趣是否有一种方法可以阻止这一切在一起,没有太多麻烦。

I have a function that 2 derived classes use, but the third doesn't, would it make sense to just leave it in the base class, even though one of the 3 derived classes doesn't use it?

The only way I could think of disallowing the third class is to basically create an intermediate class that is derived of the base, then the 2 that use the common function are derived off the second class.

Is it possible to prevent the 3rd class from using the function, while letting the two that are supposed to use it, use it?

Does that just seem to go overboard, I mean as long as I don't "try" to call the function from the 3rd class, it shouldn't be a problem, I just was interested if there was a way to prevent it all together without a lot of hassle.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

全部不再 2024-10-07 15:03:29

没有办法直接做到这一点。基本上,当你子类化时,你是说子类是基类的更具体的版本。

在这种情况下,您试图说“子类是基类的更具体版本,除了它不应该能够触及 XXX”这一事实。从本质上讲,这违反了里氏替换原则

处理此问题的最佳方法是在层次结构中添加第二个基类,我相信这就是您提到的解决方案。

基本上,建立你的层次结构:

base
 | \----   subclass without feature available
 |
 \--base+feature
       \--subclass one with specific feature
       \--subclass two with specific feature

There is not a way to do this directly. Basically, when you subclass, you're saying the subclass is a more specific version of the base class.

In this case, you're trying to say "the subclass is a more specific version of the base class, except for the fact that it shouldn't be able to touch XXX". That's, in essence, violating the Liskov Substitution Principle.

The best way to handle this is to add a second base class in your hierarchy, which is I believe the solution you mention.

Basically, make your hierarchy:

base
 | \----   subclass without feature available
 |
 \--base+feature
       \--subclass one with specific feature
       \--subclass two with specific feature
拥醉 2024-10-07 15:03:29

您可以将此功能设为虚拟。然后重写第三类中的函数并抛出异常。它将阻止开发人员使用第三类中的功能。

You can make this function virtual. Then override the function in the 3rd class and throw an exception. It will prevent developers to use the function in the 3rd class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文