纯虚函数和抽象类是C++中实现多态性的重要概念。以下是对纯虚函数和抽象类的详细解释:

纯虚函数(Pure Virtual Function):
纯虚函数是在基类中声明的没有实际实现的虚函数。
通过将函数声明为纯虚函数,可以使基类成为抽象类,这意味着它不能直接实例化对象。
子类必须实现纯虚函数,否则子类也将成为抽象类。
声明纯虚函数的语法是在函数声明末尾加上 “= 0″:virtual void functionName() = 0;
示例:
class Shape {
pubpc:
    virtual double area() const = 0; // 纯虚函数
};
class Rectangle : pubpc Shape {
private:
    double length;
    double width;
pubpc:
    Rectangle(double l, double w): length(l), width(w) {}
    double area() const override {
        return length * width;
    }
};
int main() {
    Shape* shapePtr; // 合法,使用基类指针
    // Shape shape; // 错误,抽象类无法实例化对象
    Rectangle rectangle(5, 3);
    shapePtr = &rectangle;
    cout << "Area: " << shapePtr->area() << endl;
    return 0;
}
抽象类(Abstract Class):
抽象类是包含一个或多个纯虚函数的类,无法直接实例化对象。
抽象类用于定义接口和创建一组相关的类,并确保派生类实现了基类的纯虚函数。
可以将抽象类看作是定义了一系列行为但没有具体实现的蓝图。
示例:
class Animal {
pubpc:
    virtual void makeSound() const = 0; // 纯虚函数
    void sleep() const {
        cout << "Zzz..." << endl;
    }
};
class Dog : pubpc Animal {
pubpc:
    void makeSound() const override {
        cout << "Woof!" << endl;
    }
};
int main() {
    Animal* animalPtr; // 合法,使用基类指针
    // Animal animal; // 错误,抽象类无法实例化对象
    Dog dog;
    animalPtr = &dog;
    animalPtr->makeSound();
    animalPtr->sleep();
    return 0;
}
通过纯虚函数和抽象类,可以实现多态性,允许在运行时根据实际对象类型调用相应的函数实现。抽象类定义了一组规范和行为,而派生类则提供了具体的实现。
            
            
      
      
                  
                  
                  
                  
                  
                    
                    
                    
                    
                    
                    
                    
                    
      
        
京公网安备 11010802030320号