术语“多态”(polymorphism
)是”poly
“ + “morphs
“的组合,其意味着多种形式。 这是一个希腊词。 在面向对象编程中,我们使用3
个主要概念:继承,封装和多态。
c++中有两种类型的多态:
下面来看看一个简单的c++运行时多态的例子。
#include <iostream>
using namespace std;
class animal {
public:
void eat(){
cout<<"eating...";
}
};
class dog: public animal
{
public:
void eat()
{
cout<<"eating bread...";
}
};
int main(void) {
dog d = dog();
d.eat();
return 0;
}
运行上面代码,得到以下结果 -
eating bread...
下面来看看看c++中的运行时多态性的另一个例子,下面有两个派生类。
#include <iostream>
using namespace std;
class shape {
public:
virtual void draw(){
cout<<"drawing..."<<endl;
}
};
class rectangle: public shape
{
public:
void draw()
{
cout<<"drawing rectangle..."<<endl;
}
};
class circle: public shape
{
public:
void draw()
{
cout<<"drawing circle..."<<endl;
}
};
int main(void) {
shape *s;
shape sh;
rectangle rec;
circle cir;
s=&sh;
s->draw();
s=&rec;
s->draw();
s=○
s->draw();
}
运行上面代码,得到以下结果 -
drawing...
drawing rectangle...
drawing circle...
运行时多态性可以通过c++中的数据成员来实现。 下面来看看一个例子,通过引用变量访问字段,引用变量引用派生类的实例。
#include <iostream>
using namespace std;
class animal {
public:
string color = "black";
};
class dog: public animal
{
public:
string color = "grey";
};
int main(void) {
animal d= dog();
cout<<d.color;
}
运行上面代码,得到以下结果 -
black