c++继承与多态

来源:互联网 发布:网络拓扑层级 编辑:程序博客网 时间:2024/04/30 06:28

继承

 

#include <iostream.h>
class A{
public:
 static void add(){
    cout<<"dddd"<<endl;
 }
};
class Person{
public:
 Person(int hand)
 {
  this->hand=hand;
 }
 int hand;
 void walk()
 {
  cout<<"person walk"<<endl;
 }
 void eat()
 {
  cout<<"person eat"<<endl;
 }
};
//如果public不写 能够实例化Chinese 不能调用Person的属性及方法 除非重写
//proteced外部不能访问 子类中可以访问
class Chinese : public Person{
public:
 //调用子类的构造方法时会先调用父类的构造方法 父类没有默认的构造方法 可以指定调用就是下面的方式
 Chinese():Person(20)
 {
 }
 //::表示作用域标识符 前面的参数表示哪个类的哪个资源
 void eat()
 {
  //相当于java中的super.eat(); 当类中出现static标示的属性和方法可以使用::
  A::add();
  Person::eat();
  cout<<"Chinese eat"<<endl;
 }
};

void main(){
 Chinese c;
 c.eat();
}

 

 

 

多态

 

 

#include <iostream.h>
class Person{
public:
 Person(int hand)
 {
  this->hand=hand;
 }
 int hand;
 void walk()
 {
  cout<<"person walk"<<endl;
 }
 virtual void eat()
 {
  cout<<"person eat"<<endl;
 }
 //表示一个空的虚方法 表示子类必须实现 这样表示该类 有空的虚方法就是抽象类了,不能实例化
 //相当于java中的 abstract void heart();

 virtual void heart()=0;
};

class Chinese : public Person{
public:
 Chinese():Person(20)
 {
 }

 void eat()
 {
  cout<<"Chinese eat"<<endl;
 }
 void heart(){
  cout<<"Chinese heart"<<endl;
 }
};
void toeat(Person *person)
{
 person->eat();
}
void toheart(Person *person)
{
 person->heart();
}

void main()
{
  Chinese chinese;
  Person *person=&chinese;
  //如果调用person->eat();调用的父类的eat() 如果在父类eat方法添加virtual 则调用子类的
  toeat(person);
  toheart(person);
}

原创粉丝点击