静态绑定是根椐编译时声明的变量类型,来决定调用哪个类型的函数;

动态绑定是根椐运行时实际赋给变量的值,来决定调用的是基类类或派生类的函数​。

要实现动态​绑定,必须用到虚函数,没有虚函数参与实现的多态性都不是动态绑定。但是虚函数不是实现动态绑定的唯一条件,实现动态绑定还与虚函数的访问方式有关。只有通过对象指针或对象引用 才能调用虚函数实现动态绑定。​​

#include

using namespace std;

class Transport

{

public:

virtual void setspeed(int s)//定义虚函数,设置参数

{

speed=s;

cout<<"in basic setspeed()"<<endl;

}

virtual void transport()//定义虚函数,显示状态

{

cout<<"basic transport in"<<speed<<endl;

}

private:

int speed;//私有成员

};

class Car:public Transport//public方式继承Transport

{

public:

virtual void setspeed(int s)//定义虚函数,设置参数

{

speed=s;

cout<<"in Car setspeed()"<<endl;

}

virtual void transport()//定义虚函数,显示状态

{

cout<<"Car transport in"<<speed<<endl;

}

private:

int speed;

};

class Trian:public Transport//public方式继承Transport

{

public:

virtual void setspeed(int s)//定义虚函数,设置参数

{

speed=s;

cout<<"in Trian setspeed()"<<endl;

}

virtual void transport()//定义虚函数,显示状态

{

cout<<"Trian transport in"<<speed<<endl;

}

private:

int speed;

};

void print(Transport & t)//全局函数,参数是基类的引用

{

t.transport();

}

void main()

{

Transport *pt;//定义基类对象指针

Car c;

pt=&c;//指针指向对象Car的对象c

pt->setspeed(60);//访问相应虚函数

Trian t;

pt=&t;

pt->setspeed(200);//指针指向对象Trian的对象t

print(c);//调用全局函数

print(t);

}

C++学习笔记 -动态绑定

注意:多态性机制提供了接口(函数名)与函数实现(函数体)分离的方法。这大大方便了软件的设计和维护,但多态性需要更多的额外开销。

相关文章: