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