【问题标题】:Can we declare an interface class by making all the methods abstract using the keyword ‘abstract’ in a class in C++? [duplicate]我们可以通过在 C++ 类中使用关键字“abstract”使所有方法抽象来声明接口类吗? [复制]
【发布时间】:2013-12-29 14:17:54
【问题描述】:

我想知道用这种方法在C++中定义接口类的方法。可能吗?我不想了解接口创建,但想了解 C++ 中抽象关键字的使用。

【问题讨论】:

  • C++ 中没有关键字abstract。而如果你想要一个抽象类,也就是一个不能被初始化的类,就使用一个受保护的构造函数。
  • 虽然有纯虚函数:= 0, abstract 是 C#
  • @BartekBanachewicz:不,抽象类是具有必须重写的纯虚函数的类,而不是具有受保护构造函数的类。
  • @MikeSeymour MSDN:They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented.,维基百科:an abstract type is a type in a nominative type system which cannot be instantiated directly. 。你是实现某些功能还是仅仅从它派生并不重要。
  • @BartekBanachewicz:C++11:“如果一个类至少有一个纯虚函数,那么它就是抽象的。”具有受保护构造函数(并且没有纯虚函数)的类可以直接由其成员、朋友和子类实例化,因此即使是那些相当不准确的描述也不是抽象的。

标签: c++


【解决方案1】:

在 C++ 中,接口定义如下:

class Interface {
public:
    virtual ~Interface();
    virtual void aMethod() = 0;
};

注意虚拟析构函数。

【讨论】:

    【解决方案2】:

    在 C++ 中,抽象类是任何具有至少 1 个虚函数的类。

    C++ 不直接支持接口,但您可以通过将所有函数设为公共、虚拟和抽象来实现,并且在类中没有数据成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 2013-05-22
      • 2018-05-08
      • 2023-03-16
      相关资源
      最近更新 更多