Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tại sao pure virtual function trong C++ được khởi tạo bằng 0?


Cú pháp = 0 khi khai báo pure virtual function chỉ là quy ước ngôn ngữ để chỉ "hàm này thuần ảo". Không có ý nghĩa số học. Pure virtual function chỉ khai báo, không có định nghĩa trong lớp cơ sở; lớp dẫn xuất bắt buộc ghi đè.

Ví dụ

#include <iostream>
using namespace std;

class Base { public: virtual void s() = 0; }; // Pure virtual
class Derived : public Base {
public:
    void s() override { cout << "Virtual function in Derived\n"; }
};

int main() {
    Base *b = new Derived();
    b->s(); // Gọi Derived::s()
    delete b;
    return 0;
}

Kết quả

Virtual function in Derived