純虛函數(shù)和抽象類是C++中實(shí)現(xiàn)多態(tài)性的重要概念。以下是對純虛函數(shù)和抽象類的詳細(xì)解釋:
純虛函數(shù)(Pure Virtual Function):
純虛函數(shù)是在基類中聲明的沒有實(shí)際實(shí)現(xiàn)的虛函數(shù)。
通過將函數(shù)聲明為純虛函數(shù),可以使基類成為抽象類,這意味著它不能直接實(shí)例化對象。
子類必須實(shí)現(xiàn)純虛函數(shù),否則子類也將成為抽象類。
聲明純虛函數(shù)的語法是在函數(shù)聲明末尾加上 “= 0″:virtual void functionName() = 0;
示例:
class Shape {
pubpc:
virtual double area() const = 0; // 純虛函數(shù)
};
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; // 錯誤,抽象類無法實(shí)例化對象
Rectangle rectangle(5, 3);
shapePtr = &rectangle;
cout << "Area: " << shapePtr->area() << endl;
return 0;
}
抽象類(Abstract Class):
抽象類是包含一個或多個純虛函數(shù)的類,無法直接實(shí)例化對象。
抽象類用于定義接口和創(chuàng)建一組相關(guān)的類,并確保派生類實(shí)現(xiàn)了基類的純虛函數(shù)。
可以將抽象類看作是定義了一系列行為但沒有具體實(shí)現(xiàn)的藍(lán)圖。
示例:
class Animal {
pubpc:
virtual void makeSound() const = 0; // 純虛函數(shù)
void sleep() const {
cout << "Zzz..." << endl;
}
};
class Dog : pubpc Animal {
pubpc:
void makeSound() const override {
cout << "Woof!" << endl;
}
};
int main() {
Animal* animalPtr; // 合法,使用基類指針
// Animal animal; // 錯誤,抽象類無法實(shí)例化對象
Dog dog;
animalPtr = &dog;
animalPtr->makeSound();
animalPtr->sleep();
return 0;
}
通過純虛函數(shù)和抽象類,可以實(shí)現(xiàn)多態(tài)性,允許在運(yùn)行時(shí)根據(jù)實(shí)際對象類型調(diào)用相應(yīng)的函數(shù)實(shí)現(xiàn)。抽象類定義了一組規(guī)范和行為,而派生類則提供了具體的實(shí)現(xiàn)。