虛函數是一種多態(tài)性機制,允許派生類覆蓋其基類的成員函數:聲明:在函數名前加上關鍵字 virtual。調用:使用基類指針或引用,編譯器將動態(tài)綁定到派生類的適當實現。實戰(zhàn)案例:通過定義基類 shape 及其派生類 rectangle 和 circle,展示虛函數在多態(tài)中的應用,計算面積和繪制形狀。
C++ 中的虛函數
虛函數是一種多態(tài)性機制,允許派生類覆蓋其基類的成員函數。這使程序員能夠在基類中定義通用的行為,同時仍然允許派生類為該行為提供特定于其實例的實現。
聲明虛函數
要聲明一個虛函數,請在函數名的開頭放置關鍵字 virtual
。例如:
class Base { public: virtual void print() const; };
登錄后復制
調用虛函數
調用虛函數,使用基類指針或引用。編譯器將動態(tài)綁定到派生類的適當實現。例如:
void doSomething(Base* base) { base->print(); }
登錄后復制
實戰(zhàn)案例
下面是一個使用虛函數的示例:
#include <iostream> class Shape { public: virtual double area() const = 0; virtual void draw() const = 0; }; class Rectangle : public Shape { public: Rectangle(double width, double height) : width_(width), height_(height) {} double area() const override { return width_ * height_; } void draw() const override { std::cout << "Drawing rectangle" << std::endl; } private: double width_; double height_; }; class Circle : public Shape { public: Circle(double radius) : radius_(radius) {} double area() const override { return 3.14 * radius_ * radius_; } void draw() const override { std::cout << "Drawing circle" << std::endl; } private: double radius_; }; int main() { Shape* rectangle = new Rectangle(5, 10); Shape* circle = new Circle(5); std::cout << rectangle->area() << std::endl; // Output: 50 std::cout << circle->area() << std::endl; // Output: 78.5 rectangle->draw(); // Output: Drawing rectangle circle->draw(); // Output: Drawing circle return 0; }
登錄后復制