实验目的和要求
了解静态联编的动态联编的概念。掌握动态联编的条件。
实验内容
1.分析并调试下列程序。
-
//sy6_1.cpp
-
-
using namespace std;
-
class Base
-
{
-
public:
-
virtual void f(float x){ cout<< "Base::f(float)"<<x<< endl;}
-
void g(float x){ cout<< "Base::g(float)"<<x<< endl;}
-
void h(float x){ cout<< "Base::h(float)"<<x<< endl;}
-
};
-
class Derived: public Base
-
{
-
public:
-
virtual void f(float x){ cout<< "Derived::f(float}"<<x<< endl;}
-
void g(int x){ cout<< "Derived::g(int)"<<x<< endl;}
-
void h(float x){ cout<< "Derived::h(float)"<<x<< endl;}
-
};
-
int main()
-
{
-
Derived d;
-
Base *pb=&d;
-
Derived *pd=&d;
-
pb->f( 3.14f); //语句1
-
pd->f( 3.14f); //语句2
-
pb->g( 3.14f); //语句3
-
pb->h( 3.14f); //语句4
-
pd->h( 3.14f); //语句5
-
return 0;
-
}
(1)找出以上程序中使用了重载和覆盖函数。
答:Base类中函数void g(); 和void h();与Derived类中的函数void g(); 和void h();函数名相同,参数类型不同,构成了函数重载。
(2)写出程序的输出结果,并解释输出结果。
程序的输出结果如下:
分析:程序首先声明一个基类Base,类中公有成员部分有虚函数f和两个成员函数g、h,接着定义派生类Derived并且继承基类中的公有部分。主函数中先声明一个对象d,接着定义指针pb。然后执行语句1,调用基类中的虚函数,输出第一行结果。接着执行语句2、3、4、5,分别调用派生类中虚函数、基类中的g函数、基类中的h函数,派生类中的h函数,输出第2、3、4、5行结果。
2
. 分析并调试下列程序
-
//sy6_3.cpp
-
-
using namespace std;
-
class Base
-
{
-
public:
-
void f(int x){ cout<<"Base::f(int)"<<x<<endl;}
-
void f(float x){ cout<<"Base::f(float)"<<x<<endl;}
-
virtual void g(void){ cout<<"Base::g(void)"<<endl;}
-
};
-
class Derived:public Base
-
{
-
public:
-
virtual void g(void){ cout<<"Derived::g(void}"<<endl;}
-
};
-
int main()
-
{
-
Derived d;
-
Base *pb=&d;
-
pb->f(42);