=0
放在類宣告中,而函數的主體則不存在。void draw()= 0;
純虛擬函式有時稱為抽象函數,而如果某個類至少有一個純虛擬函式,那麼它將被稱為抽象類。C++ 編譯器不允許範例化一個抽象類。抽象類只能被子類化,也就是說,只能使用它們作為派生其他類的基礎類別。// This program demonstrates abstract base // classes and pure virtual functions. #include <iostream> #include <memory> #include <vector> using namespace std; class Shape { protected: int posX, posY; public: virtual void draw() const =0; void setPosition(int pX, int pY) { posX = pX; posY = pY; } }; class Rectangle : public Shape { public: virtual void draw() const { cout << "Drawing rectangle at " << posX << " " << posY << endl; } }; class Hexagon : public Shape { public: virtual void draw() const { cout << "Drawing hexagon at " << posX << " " << posY << endl; } }; int main() { // Create vector of pointers to Shapes of various types vector<shared_ptr<Shape>> shapes { make_shared<Hexagon>(), make_shared<Rectangle>(), make_shared<Hexagon>() }; // Set positions of all the shapes int posX = 5, posY = 15; for (int k = 0; k < shapes.size (); k++) { shapes[k]->setPosition(posX, posY); posX += 10; posY += 10; }; // Draw all the shapes at their positions for (int j =0; j < shapes.size (); j++) { shapes[j]->draw(); } return 0; }程式輸出結果:
Drawing hexagon at 5 15
Drawing rectangle at 15 25
Drawing hexagon at 25 35
shapeArray[j]->draw();
它將在迴圈中執行不同的次數。for (int j = 0; j <shapes.size (); j ++) { shapeArray[j]->draw(); }第一次執行語句時,它將呼叫六邊形物件的 draw 函數;而第二次執行時,它將呼叫矩形物件的 draw 函數。因為這兩個 draw 函數是在不同的類中,所以它們會產生不同的行為。
=0
表示式宣告,並且沒有函數體或定義。