C++的多态性

C++的多态性分为两种,一是运行时的多态性,二是编译时的多态性,这里我就不多介绍了。代码才是做好的说明,在代码中有注释以及我的理解。不知道自己这样解释是否正确。代码如下:

//**********************************************-------------------------------------------************//

//运行时的多态性

#include<iostream>
using namespace std;
// 运行时的多态性是指直到系统运行时,才根据实际情况决定实现何种操作,
// 运行时的多态性通过虚成员实现。
// 在Person 派生出来的类Chinese 和 American 的实现方法
// 通过覆盖基类中的虚函数来实现
// C++用继承和虚函数来实现运行时的多态性。
 class Person
 {
 public:
  virtual void print(){cout<<"I'm a Preson"<<endl;}
 };

 class Chinese: public Person
 {
 public:
  virtual void print(){cout<<"I'm a Chinese"<<endl;}

 };

 class American: public Person
 {
 public: virtual void print(){cout<<"I'm a American"<<endl;}
 };

 void printPerson(Person &person)
 {
  person.print();
 }
 int main()
 {
  Person p;
  Chinese c;
  American a;
  printPerson(p);
  printPerson(c);
  printPerson(a);
  return 0;
 }

//**************************-------------------------------**********************************************//

//编译时的多态性

#include<iostream>
using namespace std;

//编译时的多态性是通过重载来实现的,对于非虚函数来说,系统在编译时,
//根据传递的参数、返回值的类型等信息决定实现何种操作

//C++用函数重载和运算符重载来实现编译时的多态性。

//重载是指同一个函数的不同版本之间参数不同


//重载
class Test
{
public:
 int add(int x, int y)
  {
   return (x + y);
  }
 float add(float x, float y)
 {
  return (x +y);
 }
};

 

//传入返回值为int
int add(int x, int y)
  {
   return (x + y);
  }
//传入 返回值为float 
float add(float x, float y)
 {
  return (x +y);
 }

int main()
{
 int i = add(1, 2);         //输出 3 正确
 float f = add(1.0f, 2.1f); //输出 3 正确

 Test test;
 int i_1 = test.add(3, 4);
 float f_1 = test.add(3.0f, 4.1f);

 cout<<"i = "<<i<<endl;
 cout<<"f = "<<f<<endl; //

 cout<<"i_1 = "<<i_1<<endl;
 cout<<"f_1 = "<<f_1<<endl;

 return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值