一、静态联编
静态联编:编译器会根据函数调用的对象类型,在编译阶段就确定函数的调用地址(早绑定)
class Animal{
public:
void speak() {
cout << "Animal Speak" << endl;
}
};
void test01() {
Animal an;
an.speak(); // 在编译阶段就就确定了调用speak这个函数
}
二、动态联编
动态联编: 在运行阶段才确定调用哪个函数(晚绑定)
动态联编的作用:可以晚绑定函数调用地址,这样可以扩展功能,可以在不修改前面代码的基础上进行项目的扩充
虚函数: 在普通成员函数前加virtual,让该函数变为虚函数,是告诉编译器这个函数要晚绑定
类型转换:
1.子类转换成父类(向上转换),编译器认为指针的寻址范围缩小了,所以是安全的
2.父类转换成子类 (向下转换),编译器认为指针的寻址范围扩大了,所以是不安全的
class Animal
{
public:
// 虚函数
virtual void speak()
{
cout << "Animal Speak" << endl;
}
};
class Dog : public Animal
{
public:
void speak()
{
cout << "Dog Speak" << endl;
}
};
class Dog1 : public Animal
{
public:
void speak()
{
cout << "Dog1 Speak" << endl;
}
};
class Dog2 : public Animal
{
public:
void speak()
{
cout << "增加技能" << endl;
}
};
void doLogin(Animal *animal)
{
animal->speak();
}
void test01()
{
Dog *dog = new Dog;
doLogin(dog);
delete dog;
Dog1 *dog1 = new Dog1;
doLogin(dog1);
delete dog1;
Dog2 *dog2 = new Dog2;
doLogin(dog2);
delete dog2;
Animal *animal = new Animal;
doLogin(animal);
delete animal;
}
void test02()
{
Animal *pA = NULL;
pA = new Dog;
doLogin(pA);
delete pA;
pA = new Dog1;
doLogin(pA);
delete pA;
pA = new Dog2;
doLogin(pA);
delete pA;
}
网友评论