C++高手帮忙 多谢

来源:百度知道 编辑:UC知道 时间:2024/05/16 13:51:47
验证静态联编的程序运行结果理解静态联编的概念。
参考程序:
#include <iostream.h>
class Point
{
public:
Point(double i,double j){x=i;y=j;}
double Area() const{return 0.0;}
private:
double x,y;
};
class Rectangle :public Point
{
public:
Rectangle(double i,double j,double k,double l);
double Area() const {return w*h;}
private:
double w,h;
};
Rectangle::Rectangle(double i,double j,double k,double l):Point(i,j)
{
w=k;h=l;
}
void fun(Point &s)
{
cout<<s.Area()<<endl;
}
void main()
{
Rectangle rec(3.0,5.2,15.0,25.0);
fun(rec);
}
问题:
将以上程序改为动态联编,分析两次结果不同的原因。
提示:把类Point 中Area()函数变为虚函数:
virtual double Area() const{return 0.0;}

快点 多谢多谢

#include <iostream.h>
class Point
{
public:
Point(double i,double j){x=i;y=j;}
virtual double Area() const{return 0.0;}//在原来的行前加了一个virtual
private:
double x,y;
};
class Rectangle :public Point
{
public:
Rectangle(double i,double j,double k,double l);
double Area() const {return w*h;}
private:
double w,h;
};
Rectangle::Rectangle(double i,double j,double k,double l):Point(i,j)
{
w=k;h=l;
}
void fun(Point &s)
{
cout<<s.Area()<<endl;
}
void main()
{
Rectangle rec(3.0,5.2,15.0,25.0);
fun(rec);
}

静态时输出结果为0,动态时输出结果为375.
静态时,func函数中的s所引用的对象执行的Area()操作被束定到Point::Area()实现代码上.这是因为,在编译阶段,对s引用的对象所执行的Area()操作只能束定到Point的函数上.
动态联编后,在运行时进行动态识别,动态联编将把func函数中的s的对象引用束定到Rectanlge类上,将执行Rectanlge类Area()的代码.由于两个类的Area()函数代码不同,故结果也不同.