純虛函數(shù)和抽象類(lèi)是C++中實(shí)現(xiàn)多態(tài)性的重要概念。以下是對(duì)純虛函數(shù)和抽象類(lèi)的詳細(xì)解釋?zhuān)?p style="text-align: center;">
純虛函數(shù)(Pure Virtual Function):
純虛函數(shù)是在基類(lèi)中聲明的沒(méi)有實(shí)際實(shí)現(xiàn)的虛函數(shù)。
通過(guò)將函數(shù)聲明為純虛函數(shù),可以使基類(lèi)成為抽象類(lèi),這意味著它不能直接實(shí)例化對(duì)象。
子類(lèi)必須實(shí)現(xiàn)純虛函數(shù),否則子類(lèi)也將成為抽象類(lèi)。
聲明純虛函數(shù)的語(yǔ)法是在函數(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; // 合法,使用基類(lèi)指針
// Shape shape; // 錯(cuò)誤,抽象類(lèi)無(wú)法實(shí)例化對(duì)象
Rectangle rectangle(5, 3);
shapePtr = &rectangle;
cout << "Area: " << shapePtr->area() << endl;
return 0;
}
抽象類(lèi)(Abstract Class):
抽象類(lèi)是包含一個(gè)或多個(gè)純虛函數(shù)的類(lèi),無(wú)法直接實(shí)例化對(duì)象。
抽象類(lèi)用于定義接口和創(chuàng)建一組相關(guān)的類(lèi),并確保派生類(lèi)實(shí)現(xiàn)了基類(lèi)的純虛函數(shù)。
可以將抽象類(lèi)看作是定義了一系列行為但沒(méi)有具體實(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; // 合法,使用基類(lèi)指針
// Animal animal; // 錯(cuò)誤,抽象類(lèi)無(wú)法實(shí)例化對(duì)象
Dog dog;
animalPtr = &dog;
animalPtr->makeSound();
animalPtr->sleep();
return 0;
}
通過(guò)純虛函數(shù)和抽象類(lèi),可以實(shí)現(xiàn)多態(tài)性,允許在運(yùn)行時(shí)根據(jù)實(shí)際對(duì)象類(lèi)型調(diào)用相應(yīng)的函數(shù)實(shí)現(xiàn)。抽象類(lèi)定義了一組規(guī)范和行為,而派生類(lèi)則提供了具體的實(shí)現(xiàn)。