首页 > 代码库 > C++继承与多态示例

C++继承与多态示例

#include <iostream>
#include <string>


using namespace std;


class Pet {
  protected:
	string name;
  public:
      void setname(string aname) {
	    this->name = aname;
	  }
	  
	  virtual string bark() {
		return name + ", Hello";
	  }
};


class Dog : public Pet {
  public:
	  virtual string bark() {
		string tmp = Pet::bark();
		return tmp + ", dog";
	}
};




int main() {
  Dog d;
  d.setname("doga");
  cout << d.bark() << endl;
  return 0;
}

C++继承与多态示例