c++继承与多态

继承

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值