为什么这个纯虚方法不编译?

Why is this pure virtual method not compiling?

我使用纯虚拟方法,如下面的代码所示。

#include <iostream>
using namespace std;
class Advertisment
{
public:
   vitual void price (int Uchrg, int no_of_unt) = 0;
   {
   }
};

class TVadvertisment : public Advertisment
{
public:
   void price (int Uchrg, int no_of_unt)
   {
      int adPrice = Uchrg * no_of_unt;
      cout << "Advertisment Price: " << adPrice;
   }
};

int main()
{
   TVadvertisment T;
   T.price(1000, 60);
   return 0;
}

据我所知,纯虚函数将被声明为 virtual void display() = 0;。但是 Code::Blocks 编译器会因为这个 = 0 而显示错误。否则它将编译成功。

而且我也没有使用指针来调用派生的方法 class。

您的函数是纯虚拟的,这意味着该方法是虚拟的,甚至没有在基 class (= 0) 中实现。 所以你必须删除它后面的块。

必须是:

virtual price(int Uchrg, int no_of_unt) = 0;

没有 { }.

Virtual 意味着,从基础 class 继承的 classes 可以覆盖方法并通过基础 class 接口调用。如果一个 class 有一个纯虚方法,那么 class 是抽象的,这个函数需要被 class 继承自该基类 class 的 es 覆盖以被实例化。

简而言之:

虚拟:

virtual price(int Uchrg, int no_of_unt)
{
   // Implementation
}

有一个实现是基础class。 Sub classes not 不需要覆盖,但他们可以。 class 不是抽象的,可以实例化。

纯虚:

virtual price(int Uchrg, int no_of_unt) = 0; // No implementation

没有实现,子 classes 必须覆盖它才能不抽象。

通过基调用虚方法class:

Base* pBase = new Derived;
pBase->fun();

该方法是通过基 class 的接口调用的,但它将是派生的 class 方法。