在C ++中设计ABC(抽象基类)的良好实践 [英] Good practice to design a ABC(Abstract Base Class) in C++

查看:132
本文介绍了在C ++中设计ABC(抽象基类)的良好实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,我们可以定义不同的接口,然后我们可以为具体类实现多个接口。

In java, we can define different interfaces and then later we can implement multiple interface for a concrete class.

// Simulate Java Interface in C++
/*
interface IOne {
    void   MethodOne(int i);
    .... more functions
}

interface ITwo {
    double MethodTwo();
    ... more functions
}

class ABC implements IOne, ITwo {
    // implement MethodOne and MethodTwo
}
*/

在C ++中,一般来说,我们应该避免使用多重继承,它在某些情况下的边缘。

In C++, generally speaking, we should avoid the usage of multiple inheritance, although multi-inheritance does have its edge on some situations.

class ABC {
public:
    virtual void   MethodOne(int /*i*/) = 0 {}
    virtual double MethodTwo() = 0 {}

    virtual ~ABC() = 0 {}

protected:
    ABC() {} // ONLY ABC or subclass can access it
};

问题1 >基于 ABC

Question1> Based on the design of ABC, should I improve any other things in order to make it a decent ABC?

问题2 >是真的吗?一个好的 ABC 不应该包含成员变量,而应该将变量保存在子类中?

Question2> Is it true that a good ABC should not contain member variables and instead variables should be kept in the subclasses?

Question3 >正如我在评论中指出的,如果 ABC 必须包含太多的纯函数?是否有更好的方法?

Question3> As I indicated in the comments, what if ABC has to contain too many pure functions? Is there a better way?

推荐答案


  1. 不要提供纯虚拟方法的实现,除非

  2. 不要让你的析构函数是纯虚拟的。

  3. 不要让构造函数受到保护。您不能创建抽象类的实例。

  4. 更好地隐藏源文件中的构造函数和析构函数的实现,不会污染其他对象文件。

  5. 使您的界面不可复制。

  1. Do not provide an implementation for pure virtual methods unless it is necessary.
  2. Do not make your destructor pure virtual.
  3. Do not make your constructor protected. You cannot create an instance of an abstract class.
  4. Better hide an implementation of constructor and destructor inside a source file not to pollute other object files.
  5. Make your interface non-copyable.

如果这是一个界面,最好没有任何变量。

If this is an interface, better do not have any variables there. Otherwise it would be an abstract base class and not an interface.

太多的纯函数是可以的,除非你可以使用更少的纯函数。

Too many pure functions is OK unless you can do it with less pure functions.

这篇关于在C ++中设计ABC(抽象基类)的良好实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆