/*说明静态结合和动态结合的概念*/
#include<iostream>
using namespace std;
class test1
{
int x;
int y;
public:
test1():x(0),y(0)
{
}
test1(int a,int b):x(a),y(b)
{
}
void disp()
{
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
}
};
class test2:public test1
{
int z;
public:
test2():test1()
{
z=0;
}
test2(int a,int b,int c):test1(a,b)
{
z=c;
}
void disp()
{
test1::disp();
cout<<"z="<<z<<endl;
}
};
int main()
{
test1 p(1,2),*r;
test2 q(10,20,30);
cout<<"===p"<<endl;
p.disp();
cout<<"===q"<<endl;
q.disp();
cout<<"===*r->p"<<endl;
r=&p;
r->disp();
cout<<"===*r->q"<<endl;
r=&q;
r->disp();
}
我们定义了一个指向基类的指针*r,我们把派生类的类对象的基址赋给r,当我们调用r->disp();
的时候,本应该调用的是派生类的disp函数,根据结果我们知道实际是调用了基类的disp函数。这是为什么?
因为我们定义了r是指向基类的指针test1 *r;
所以在编译的时候决定了r与test1类相结合的关系。这种结合叫做静态结合。这种结合方式在程序的运行中是不能改变的。