简体   繁体   English

通过其方法的子集实现接口

[英]Implementing an interface through a subset of its methods

I have a C++ interface with two methods. 我有两种方法的C ++接口。 Any class implementing this interface need to implement at least one of the two methods but may define both. 任何实现此接口的类都需要实现这两种方法中的至少一种,但可以同时定义这两种方法。 It is however not necessary to define both. 但是,不必同时定义两者。 What is the best pattern to use in such situation ? 在这种情况下使用的最佳模式是什么?

Something like following: 如下所示:

class MyInterface
{
public:
  virtual ~MyInterface() {}

  virtual void foo() = 0;
  virtual void bar() = 0;
};


class MyAbstractClass :  public MyInterface
{
public:
  virtual ~MyAbstractClass();

  // Provide implementation for foo or bar
  virtual void foo() override { }
  virtual void bar() override { }
};

class MyNewClass : public MyAbstractClass
{
   // Implement either of foo or bar or can be both
};

IMHO the question is already wrong and also the class it is based on. 恕我直言,这个问题已经是错误的,并且它是基于的类。

Case A: A class has a definition for a given method. 案例A:一个类具有给定方法的定义。 The base implementation should provide an expectable behavior. 基本实现应提供预期的行为。 In this case you are free to override it or not. 在这种情况下,您可以随意覆盖或不覆盖它。

Case B: The method is abstract so you have to overwrite it in an expectable manner, otherwise the compiler won't compile. 情况B:该方法是抽象的,因此您必须以预期的方式覆盖它,否则编译器将无法编译。

There is no way to declare a "please overwrite one or both" in C++. 在C ++中无法声明“请覆盖一个或两个”。 A class given, which expect that, is (very) bad design. 给定一个期望的类是(非常)糟糕的设计。

So the question does not exist. 所以这个问题不存在。 If it exists, it is not possible to answer it with more details, as it depends on the context. 如果存在,则不可能更详细地回答它,因为它取决于上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM