首页 > 代码库 > 一个C++继承、虚函数和多态性的实例代码

一个C++继承、虚函数和多态性的实例代码

#include <iostream>
#include <string>

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;
}

一个C++继承、虚函数和多态性的实例代码