码迷,mamicode.com
首页 > 编程语言 > 详细

C++三大特征总结

时间:2015-08-08 11:52:02      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

  • 继承
  • 封装
  • 多态
  1. 定义

不同对象做同一种操作,产生不同的结果,称为多态。

  1. 多态分为

静态(编译时)的多态,例如函数重载(非虚函数);

动态(运行时)的多态。通过虚函数实现的。即用派生类的同名函数覆盖基类的虚函数。

 编译时多态:函数重载

函数重载是一系列具有相同或者相似功能,但数据类型或参数不同的同名函数。

重载举例:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 
 6 class test 
 7 
 8 {
 9 
10   public :
11 
12     int add (int x , int y) 
13 
14     {
15                 return (x+y);
16             }
17             
18             float add (float x , float y )
19             {
20                 return (x+y);
21             }
22 };
23 
24 
25 int main(int argc , char * argv[] )
26 {
27    test t;
28     
29    int  i1 = t.add(1,2);
30    float i2 = t.add(3.3f,4.4f);
31    
32    cout<<"i1="<<i1<<endl;
33    cout<<i2="<<i2<<endl;
34 }
35     

 

 

  1. 运行时多态:虚函数原理

虚函数表。如果一个类含有虚函数,系统会为这个类分配一个指针指向一张虚函数表,表中每一项指向一个虚函数的地址,在实现上就是一个函数指针的数组。

举例:

 1 include <iostream>
 2 using namespace std;
 3 
 4 class person {
 5     pubic:
 6         virtual void print() {cout<<"I‘m a person" <<endl;}
 7 };
 8 
 9 class Chinese:public person {
10     pubic:
11         virtual void print(){cout<<"I‘m from china"<<endl;}
12 };
13 
14 class America:public person{
15     publc:
16         virtual void print(){cout<<Im from USA"<endl;}
17 };
18 
19 void printPerson(person &person){
20     person.print();
21 }
22 
23 int main()
24 {
25     person p;
26     Chinese c;
27     America a;
28     
29     printPerson(p);
30     printPerson(c);
31     printPerson(a);
32     
33     return 0;   
34 }  

 

C++三大特征总结

标签:

原文地址:http://www.cnblogs.com/fysola/p/4712707.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!