今天来总结一些c++中,有关多态的知识。
多态:
多态可以简单地概括为“一个接口,多种方法”,程序在运行时才决定调用的函数,它是面向对象编程领域的核心概念。
接下来,我写一个简单地函数来说明多态:
#include<iostream>
using namespace std;
int Add(int left, int right)
{
return left + right;
}
float Add(float left, float right)
{
return left + right;
}
int main()
{
cout<<Add(1,2)<<endl;
cout<<Add(1.11f,2.22f)<<endl;
//cout<<Add(1,2.22f)<<endl;
return 0;
}
上面的cout<<Add(1,2.22f)<<endl编译是通不过的,应为编译器不知道到底要将传递的参数转化为double类型还是int类型,如果,想要它编译通过,可以屏蔽掉任何一个Add函数。
这里也很容易看出来,系统会根据不同的参数调用不同的Add函数。以上属于静态多态。
动态多态
动态绑定:在程序执行期间(非编译期)判断所引用对象的实际类型,根据其实际类型调用相应的方法。使用virtual关键字修饰类的成员函数时,指明该函数为虚函数,派生类需要重新实现,编译器将实现动态绑定。
例子:
#include<iostream>
using namespace std;
#include <time.h>
#include <Windows.h>
#define random(x) (rand()%x)
class WashRoom
{
public:
void GotoManWash()
{
cout<<"go--left-----man"<<endl;
}
void GotoWomanWash()
{
cout<<"go--right----woman"<<endl;
}
};
class Person
{
public:
virtual void GotoWash(WashRoom& _wash) = 0;
};
class Man:public Person
{
public:
void GotoWash(WashRoom& _wash)
{
_wash.GotoManWash();
}
};
class Woman:public Person
{
public:
void GotoWash(WashRoom& _wash)
{
_wash.GotoWomanWash();
}
};
int main()
{
WashRoom _w;
for (int idx = 0;idx < 10;idx++)
{
Person* _p;
srand((int)time(0));
int i = random(10);
if (i&0x01)
{
_p = new Man;
}
else
{
_p = new Woman;
}
_p->GotoWash(_w);
delete _p;
_p = NULL;
Sleep(1000);
}
}
其中,Person类仅仅提供一个接口。
下面来看一些代码:
class B
{
public:
virtual void FunTest1()
{
cout<<"B::FunTest1()"<<endl;
}
void FunTest2()
{
cout<<"B::FunTest2()"<<endl;
}
virtual void FunTest3()
{
cout<<"B::FunTest3()"<<endl;
}
virtual void FunTest4()
{
cout<<"B::FunTest4()"<<endl;
}
virtual void FunTest4(int)
{
cout<<"B::FunTest4(int)"<<endl;
}
};
class D:public B
{
public:
virtual void FunTest1()
{
cout<<"D::FunTest1()"<<endl;
}
virtual void FunTest2()
{
cout<<"D::FunTest2()"<<endl;
}
void FunTest3()
{
cout<<"D::FunTest3()"<<endl;
}
virtual void FunTest4()
{
cout<<"D::FunTest4()"<<endl;
}
};
int main()
{
B* b;
D d;
b = &d;
b->FunTest1();
b->FunTest2();
b->FunTest3();
b->FunTest4();
b->FunTest4(1);
//cout<<sizeof(D)<<endl;
return 0;
}
主函数中调用的,到底是基类里面的还是派生类里面的呢?
运行结果:
D::FunTest1()
B::FunTest2()
D::FunTest3()
D::FunTest4()
B::FunTest4(int)
从结果可以推断:
基类里面带virtual的函数,在继承类中会被重写(派生类里面的virtual可以省略);
若基类里面不带virtual,派生类里面没有带,则没有被重写,仅仅被继承了写来;
另外,带参数和不带参数也不一样。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)