0

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

我在编译器中检查了它,我收到警告说“它没有覆盖器”。因此,如果我必须在辅助类中覆盖这个纯虚拟方法(在抽象类中定义),我该如何使用基本类中的这个定义?没用吗?

4

3 回答 3

1

您是否正在寻找这样的东西:

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
  }
};
于 2015-05-31T18:49:44.960 回答
1

这是一个解释纯函数概念的示例

#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 不是抽象的,因为它将虚函数重新声明为非纯虚函数。

于 2015-05-31T19:13:23.010 回答
0

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

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

于 2015-05-31T18:54:45.097 回答