c++继承与多态

本文通过具体的C++代码示例介绍了类的继承机制,包括如何定义基类和派生类,以及如何在派生类中重写基类的方法。此外,还详细解释了多态的概念,并展示了如何通过虚函数实现运行时多态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值