抽象类和纯方法

Abstract class and pure method C++

本文关键字:方法 抽象类      更新时间:2023-10-16

我在Stephen Prata的《c++ Primer Plus VI Edition》一书中读到,我可以在抽象类中编写纯方法的定义。我知道我可以写,例如,void pure() = 0,然后我可以在这门课上定义这个方法。我认为= 0只是为了使类抽象,如果我从该类继承另一个类,我不必覆盖它(我不知道"覆盖"这个词是否正确,我的意思是我不想通过在二级类中编写具有相同名称的方法来隐藏基本类的方法)。

我在编译器中检查了它,我得到警告,"它没有覆盖"。因此,如果我必须在二级类中覆盖这个纯虚方法(在抽象类中定义),我如何使用基本类中的定义?这没用吗?

你在找这样的东西吗?

class Abstract {
public:
  virtual void f() = 0;
};
// A pure virtual function can still be defined.
// It has to be defined out-of-class.
void Abstract::f() {
  // Do something
}
class Concrete : public Abstract {
public:
  void f() {
    Abstract::f();  // call base class implementation
    // Do something more
  }
};

下面是一个解释纯函数概念的例子

#include <iostream>
struct A
{
    virtual ~A() = default;
    virtual void what() const = 0;
};
void A::what() const 
{ 
    std::cout << "struct A"; 
}
struct B : A
{
    virtual void what() const = 0;
};
void B::what() const 
{ 
    A::what();
    std::cout << ", struct B : A"; 
}
struct C : B
{
    void what() const;
};
void C::what() const 
{ 
    B::what();
    std::cout << ", struct C: B"; 
}

int main() 
{
//  A a; compiler error
//  B b; compiler error
    C c;
    const A &rc = c;
    rc.what();
    std::cout << std::endl;
    return 0;
}

程序输出为

struct A, struct B : A, struct C: B

在这个例子中,类A和类B是抽象的,因为它们有一个纯虚函数,尽管它们每个都提供了它们的纯虚函数的相应定义。

只有类C不是抽象的,因为它将虚函数重新声明为非纯虚函数。

如果要实例化继承的类,即创建该类型的对象,则必须在继承的类中实现所有纯虚方法。

换句话说,纯虚方法不仅定义类接口,而且还强制您提供它们的实际实现。