46.动态联编和静态联编
1.动态联编和静态联编(重点难点)
1.静态联编
编译器会根据函数调用的对象类型,在编译阶段就确定函数的调用地址,这就是静态联编(早绑定)
2.虚函数
在普通成员函数前面加virtual,该函数变为虚函数,是告诉编译器这个函数要晚绑定
3.动态联编
在运行阶段才确定调用哪个函数(晚绑定),
4.动态编译的作用,可以晚绑定函数调用地址,这样可以扩展功能,不修改前面的代码的基础上进行项目的扩充
5.类型转换问题
1.子类转换成父类(向上转换):编译器认为指针的寻址范围缩小了,所以是安全的
2.父类转换成子类(向下转换);编译器认为指针的寻址范围扩大了,不安全
2.视频内容
程序1:
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
class Animal
{
public:
void speak()
{
cout << "Animal speak " << endl;
}
};
void test()
{
Animal an;
an.speak();//在编译阶段就确定调用speak这个函数
}
int main()
{
test();
system("pause");
return EXIT_SUCCESS;
}
输出结果:
Animal speak
请按任意键继续. . .
程序2:
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
class Animal
{
public:
void speak()
{
cout << "Animal speak " << endl;
}
};
class Dog: public Animal
{
public:
void speak()
{
cout << "Dog speak" << endl;
}
};
void doLogin(Animal *animal)
{
animal->speak();
}
void test01()
{
Animal an;
an.speak();//在编译阶段就确定调用speak这个函数
}
void test02()
{
Dog *dog = new Dog;
doLogin(dog);
}
int main()
{
test02();
system("pause");
return EXIT_SUCCESS;
}
输出结果:
Animal speak
请按任意键继续. . .
程序3:
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
class Animal
{
public:
//虚函数
virtual void speak()
{
cout << "Animal speak " << endl;
}
};
class Dog: public Animal
{
public:
void speak()
{
cout << "Dog speak" << endl;
}
};
void doLogin(Animal *animal)
{
animal->speak();
}
void test01()
{
Animal an;
an.speak();//在编译阶段就确定调用speak这个函数
}
void test02()
{
Dog *dog = new Dog;
doLogin(dog);
}
int main()
{
test02();
system("pause");
return EXIT_SUCCESS;
}
输出结果:
Dog speak
请按任意键继续. . .
程序4:
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
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;
}
};
void doLogin(Animal *animal)
{
animal->speak();
}
void test01()
{
Animal an;
an.speak();//在编译阶段就确定调用speak这个函数
}
void test02()
{
Dog *dog = new Dog;
doLogin(dog);
Dog1 *dog1 = new Dog1;
doLogin(dog1);
}
int main()
{
test02();
system("pause");
return EXIT_SUCCESS;
}
输出结果:
Dog speak
Dog1 speak
请按任意键继续. . .