1、多态性具体来说:就是同一个函数名称,作用在不同的对象产生不同的 ,主要针对的是基类和多个派生类之间的关系
例子:
#include<iostream>
using namespace std;
class animal
{
public:
void sleep()
{
cout << "aniaml is sleeping" << endl;
}
void breath()
{
cout << "aniaml is breathing" << endl;
}
};
class fish :public animal
{
public:
void breath()
{
cout << "fish is breathing" << endl;
}
};
int main()
{
fish fh;
animal* an = &fh;
an->breath();
fh.breath();
system("pause");
return 0;
}
在例子中,定义了一个fish和animal类的对象,并且将fish类的对象赋值给animal类的对象an,。。。这里是指针变量,将fh的地址赋给了an,按照我们的理解
an对象调用的函数应该是属于fh地址中的函数,应该调用fish::breath()函数,,,但是在c++编译的过程中,编译器进行了类型的转换,此时c++编译器认为
an对象保存的是animal对象的地址,而不是指针变量指向的fh的地址,,,,所以函数调用的是animal::breath()函数。
在构造fish类的对象时,系统首先调用的是aniaml;类的构造函数取构造animal类的对象,然后才去调用fish类的对象,,当fish;类对象转换成aniaml
对象时,该对象被认为是元对象整个内存模型中的上半部分(fish对象的内存包含(类aniam累的对象站的内存和类fish对象自身占的额内存)),主要是因为fish类
是继承animal类的,fish的对象j中包含animal类的函数以及成员。
2、静态多态性
函数的重载主要有两种:
1、函数相同,但是参数的个数和参数类型不同
2、函数的参数相同但是属于不同的类
调用形式: 对象名。函数 或者 函数名前加上类::,作用域符::,表示调用这个类的::函数
#include<iostream>
using namespace std;
class point
{
int x, y;
public:
point(int a, int b)
{
x = a;
y = b;
}
double area()
{
return 0;
}
};
class circle :public point
{
int r;
public:
circle(int a, int b,int c) :point(a, b), r(c)
{}
double area(){
return 3.14*r*r;
}
};
int main()
{
point pob(16, 15);
circle cob(20, 20, 10);
cout << "pob.area" << pob.area() << endl;
cout << "cob.area()" << cob.area() << endl;
cout << cob.point::area() << endl;//表示派生类对象调用基类成员函数
system("pause");
return 0;
}