强制派生类调用基函数

发布于 2024-08-14 16:05:15 字数 430 浏览 2 评论 0原文

如果我从另一个类派生一个类并覆盖一个函数,我可以通过在派生类中的 myFunc 实现中调用 Base::myFunction() 来调用基函数。

但是,有没有一种方法可以在我的 Base 类中定义在任何情况下都调用基函数,并且无需在覆盖函数中显式调用它? (在执行派生函数之前或之后)

或者更好,如果我的虚拟 Base 类中有一个虚拟函数,以及两个实现的私有函数 before() 和 < code>after(),是否可以在Base类中定义在调用该Base类的任何派生类中的函数之前和之后, before()after() 会被调用吗?

谢谢!

If I derive a class from another one and overwrite a function, I can call the base function by calling Base::myFunction() inside the implementation of myFunc in the derived class.

However- is there a way to define in my Base class that the base function is called in any case, also without having it called explicitly in the overwritten function? (either before or after the derived function executed)

Or even better, if I have a virtual function in my virtual Base class, and two implemented private functions before() and after(), is it possible to define in the Base class that before and after the function in any derived class of this Base class is called, before() and after() will be called?

Thanks!

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

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

发布评论

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

评论(3

尴尬癌患者 2024-08-21 16:05:15

不,这是不可能的。
但是您可以通过调用不同的虚拟函数来模拟它,如下所示:

class Base
{
public:
  void myFunc()
  {
    before();
    doMyFunc();
    after();
  }

  virtual void doMyFunc() = 0;
};

No, this is not possible.
But you can simulate it by calling a different virtual function like so:

class Base
{
public:
  void myFunc()
  {
    before();
    doMyFunc();
    after();
  }

  virtual void doMyFunc() = 0;
};
单调的奢华 2024-08-21 16:05:15

您试图阻止派生类重载/覆盖基类中的方法。您可以通过将方法标记为“不可重写”(取决于语言)来鼓励它,但总有一种方法可以解决它。

换句话说,你不能强迫某人以特定的方式使用你的类,只能告诉他们应该如何使用你的类。

You're trying to prevent a derived class from overloading/overriding a method in the base. You can encourage it by marking methods as 'not overridable' (depending on the language), but there's always a way around it.

In other words, you can't force someone to use your class in a particular way, only tell them the way it should be used.

绳情 2024-08-21 16:05:15

对于 C++ 来说,您不能以您想要的方式“无形地”调用继承的函数。

通过继承类向下调用的唯一方法是构造函数和析构函数。

Answering for C++, you cannot have an inherited function "invisibly" called in the way you want.

The only methods that call down through inherited classes are constructors and destructors.

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