c++纯虚拟函数与实体

c++ pure virtual functions with a body

本文关键字:实体 函数 虚拟 c++      更新时间:2023-10-16

我最近了解到,在C++中,纯虚拟函数可以有一个主体。

我知道虚函数体的存在是因为我想从派生类中调用它,但我能做到吗?

class Base{
    int x;
  public:
    virtual void print()=0;
};
void Base::print(){
  cout << x;
}
class Derived : public Base{
      int y;
  public:
      void print(){
          Base::print();
          cout << y;
      }
};

结果是:x的值,然后是y的值?

我真正的意思是,函数Base::print()将知道从派生类中的函数中获取x的值????

以下代码的输出将为"12",因此是的,将调用带有主体的纯虚拟函数,然后调用派生的print。所以,是的,结果是:x的值,然后是y的值,正如你所猜测的那样。这是有效的C++,是的,它将知道如何在该上下文中获得"x"。

有效C++"Scott Meyers提到了纯虚拟函数具有主体的原因:实现该纯虚拟函数的派生类可以在其代码中调用该实现smwhere。如果两个不同派生类的部分代码相似,则在层次结构中向上移动它是有意义的,即使该函数应该是纯虚拟的。

#include <iostream>
using namespace std;
class Base{
    int x;
  public:
    Base(): x(1) {}
    virtual void print()=0;
};
void Base::print(){
  cout << x;
}
class Derived : public Base{
      int y;
  public:
      Derived(): Base(), y(2) {}
      void print(){
          Base::print();
          cout << y;
      }
};
int main()
{
    Derived d;
    d.print();
    return 0;
}

输出:12

抽象函数当然可以有一个实现,如果是抽象析构函数,甚至要求函数仍然实现(毕竟,使析构函数virtual并不意味着只调用派生的析构函数)。。。抽象函数的实现仍然只是一个可以访问其类的成员的正常函数。

在您的示例中,xBase的成员。Base::print()访问Base的私人成员有什么令人惊讶的?