=====================
#include
#include
using namespace std;
class Pet {
public:
virtual string speak() const { return "Pet!"; }
};
class Dog : public Pet {
public:
string speak() const { return "Bark!"; }
};
class Cat : public Pet {
public:
string speak() const { return "Miao!"; }
};
void doSpeak(Pet &animal){
cout << animal.speak() << endl;
}
int main() {
Dog dog;
Cat cat;
Pet pet;
//Late binding for both:
doSpeak(dog);
doSpeak(cat);
doSpeak(pet);
return 0;
}
==================
output結果:
Bark!
Miao!
Pet!
==================
若Pet中的speak( ) 不宣告為virtual,則output:
Pet!
Pet!
Pet!
==================
Dog跟Cat是繼承自Pet這個base class,
經由virtual的宣告,可以在doSpeak中藉由傳進來的類別(Dog or Cat)判斷要做誰的doSpeak();
若Dog或Cat中,不去override speak這個function,當然都會output: Pet!
若將Pet中的speak() 改寫成virtual string speak() const = 0;
( = 0是pure virtual funcion的關鍵字)
則該virtual function會變成pure virtual function,
進而讓Pet這個class變成abstract class,
在程式中宣告任何Pet的Instance都會造成compile error,
一定要有derived class才能去宣告該class的instance。
#include
#include
using namespace std;
class Pet {
public:
virtual string speak() const { return "Pet!"; }
};
class Dog : public Pet {
public:
string speak() const { return "Bark!"; }
};
class Cat : public Pet {
public:
string speak() const { return "Miao!"; }
};
void doSpeak(Pet &animal){
cout << animal.speak() << endl;
}
int main() {
Dog dog;
Cat cat;
Pet pet;
//Late binding for both:
doSpeak(dog);
doSpeak(cat);
doSpeak(pet);
return 0;
}
==================
output結果:
Bark!
Miao!
Pet!
==================
若Pet中的speak( ) 不宣告為virtual,則output:
Pet!
Pet!
Pet!
==================
Dog跟Cat是繼承自Pet這個base class,
經由virtual的宣告,可以在doSpeak中藉由傳進來的類別(Dog or Cat)判斷要做誰的doSpeak();
若Dog或Cat中,不去override speak這個function,當然都會output: Pet!
若將Pet中的speak() 改寫成virtual string speak() const = 0;
( = 0是pure virtual funcion的關鍵字)
則該virtual function會變成pure virtual function,
進而讓Pet這個class變成abstract class,
在程式中宣告任何Pet的Instance都會造成compile error,
一定要有derived class才能去宣告該class的instance。
文章標籤
全站熱搜
