這是一個很好的例子Polymorphism。
總之,多態性允許兩種不同的類型(類)提供與不同底層實現相同的接口。
與其以A和B爲例,考慮兩個類摩托車和汽車。 摩托車和汽車可以驅動,對不對?你駕駛這兩輛車的方式是非常不同的。這兩個類應提供一個驅動器()方法,雖然他們的實現是不同的。
class Vehicle {
public:
virtual void drive() = 0;
}
class Car : public Vehicle {
public:
void drive() {
// Driving to work, however a car does that.
};
}
class Motorcycle : public Vehicle {
public:
void drive() {
// Driving to work, however a motorcycle does that.
};
}
Vehicle *car = new Car;
Vehicle *motorcycle = new Motorcycle;
// We can both be driven, so we share the same interface.
car->drive();
motorcycle->drive();
這在將對象傳遞給函數時特別有用。你有一個實現正在工作的功能。你真的不在乎如何你開始工作,只要你以某種方式駕駛。
void driveToWork(Vehicle *vehicle) {
vehicle->drive();
}
driveToWork(new Car);
// It's Tuesday, your car broke down!
// As long as we use a Vehicle to get to work, all is well.
driveToWork(new Motorcycle);
你需要理解多態背後的整體思想......下面的鏈接可能有幫助... http://stackoverflow.com/questions/1031273/what-is-polymorphism-what-is-it-for-and如何使用 – Tejendra
看看這個:http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list雖然任何書上的基本oop應解釋的概念。 – user2079303
我在[我的回答](http://stackoverflow.com/a/27099751/464581)中給出了你鏈接到的問題的具體例子。 –