#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
13-6在运行时的静态联编
注:参考对比小节“C++ 虚函数 3--虚函数应用编程 动态联编/运行时联编”
1) 静态联编:被调函数和调用函数的关系,以及它们内存地址在编译时
都已经确立好,运行时不再发生变化。只需传递参数,执行确定好的函数。
已然确定了调用与被调用的关系,代码在编译与执行时,效果都一样。
2) 动态联编:运行时,需要对各个对象的函数进行追踪。
编译程序在编译阶段并不知道将要调用的函数,只有在程序执行时才能确定
将要调用的函数。这叫做动态联编,或者动态束定,又叫晚期联编。
---------------------------------*/
class A
{
public:
// virtual int get() //若有virtual修饰,后面的代码就是属于“在编译时的动态联编”类型
//这一点,情况跟小节“C++ 虚函数 3--虚函数应用编程 动态联编/运行时联编”一样
int get() //若无virtual修饰,后面的代码就是属于“在运行时的静态联编”类型
{return 1;}
};
class B:public A
{
public:
int get()
{return 2;}
};
int main()
{
while(1)
{
cout<<"1父类 2子类 3退出: ";
int choice;
cin>>choice;
A *p;
bool quit =false;
switch(choice)
{
case 1: p=new A;
break;
case 2: p=new B;
break;
case 3: quit=true;
break;
default: cout<<"请输入1、2或者3: ";
break;
}
if(true==quit)
break;
cout<<p->get()<<endl;
}
return 0;
}
运行结果:
情况一:
1父类 2子类 3退出: 2
1
1父类 2子类 3退出: 1
1
1父类 2子类 3退出: 3
Press any key to continue
情况二:
class A中的int get() 如果有virtual修饰,运行结果如下:
1父类 2子类 3退出: 1
1
1父类 2子类 3退出: 2
2
1父类 2子类 3退出: 3
Press any key to continue
C++ 虚函数 5--2 在运行时的静态联编、在编译时的动态联编
最新推荐文章于 2022-05-02 00:15:00 发布