虛函數(shù)是一種多態(tài)性機(jī)制,允許派生類覆蓋其基類的成員函數(shù):聲明:在函數(shù)名前加上關(guān)鍵字 virtual。調(diào)用:使用基類指針或引用,編譯器將動(dòng)態(tài)綁定到派生類的適當(dāng)實(shí)現(xiàn)。實(shí)戰(zhàn)案例:通過定義基類 shape 及其派生類 rectangle 和 circle,展示虛函數(shù)在多態(tài)中的應(yīng)用,計(jì)算面積和繪制形狀。
C++ 中的虛函數(shù)
虛函數(shù)是一種多態(tài)性機(jī)制,允許派生類覆蓋其基類的成員函數(shù)。這使程序員能夠在基類中定義通用的行為,同時(shí)仍然允許派生類為該行為提供特定于其實(shí)例的實(shí)現(xiàn)。
聲明虛函數(shù)
要聲明一個(gè)虛函數(shù),請?jiān)诤瘮?shù)名的開頭放置關(guān)鍵字 virtual
。例如:
class Base { public: virtual void print() const; };
登錄后復(fù)制
調(diào)用虛函數(shù)
調(diào)用虛函數(shù),使用基類指針或引用。編譯器將動(dòng)態(tài)綁定到派生類的適當(dāng)實(shí)現(xiàn)。例如:
void doSomething(Base* base) { base->print(); }
登錄后復(fù)制
實(shí)戰(zhàn)案例
下面是一個(gè)使用虛函數(shù)的示例:
#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; }
登錄后復(fù)制