一個C++繼承、虛函數和多態性的實例代碼
#include
#include
using namespace std;
namespace Animals {
class Dog {
private:
string name;
public:
Dog(string name) : name(name) {
}
Dog() : name(NULL) {
}
virtual void bark() {
cout << "Baseclass: Hi, " << name << endl;
}
string getName() {
return name;
}
void setV(string aname) {
name = aname;
}
};
class SDog : public Dog {
public:
SDog(string name) : Dog(name){}
virtual void bark() {
Dog::bark();
cout << "Dericed Class: Hi, " << Dog::getName() << endl;
}
};
}
int main() {
using namespace Animals;
Dog a("martin");
SDog b("merry");
a.bark();
b.bark();
return 0;
}