Untitled Document

三、简答题
1．源程序
class A
{
int a;
int b;
public:
A(int m,int n):a(m),b(n) {}
int geta() {return a; }
int getb() {return b; }
};

class B :public A
{
public:
B(int m,int n):A(m,n) {}
int geta() {return A::geta()*2; }
};

void main()
{
B b(2,2);
b.geta();
}
2、源程序
#include "iostream.h"
class A
{
int a;
int b;
public:
A(int m,int n):a(m),b(n) { cout<<"A created"<<endl; }
int geta() {return a; }
int getb() {return b; }
~A() {cout<<"A destroyed"<<endl; }
};

class B :public A
{
public:
B(int m,int n):A(m,n) { cout<<"B created"<<endl;}
int geta() {return A::geta()*2; }
~B() {cout<<"B destroyed"<<endl; }
};

void main()
{
B b(2,2);
b.geta();
}
3. 源程序
#include "iostream.h"
class A
{
int a;
int b;
public:
A(int m,int n):a(m),b(n) { cout<<"A created"<<endl; }
int geta() {return a; }
int getb() {return b; }
~A() {cout<<"A destroyed"<<endl; }
};

class B :public A
{
public:
B(int m,int n):A(m,n) { cout<<"B created"<<endl;}
int geta() {return A::geta()*2; }
~B() {cout<<"B destroyed"<<endl; }
};

void main()
{
B b(2,2);
A* pa=&b;
b.geta();
pa->geta();
}
4. 源程序
#include "iostream.h"
class A
{
int a;
int b;
public:
A(int m,int n):a(m),b(n) { cout<<"A created"<<endl; }
virtual int geta() {return a; }
virtual int getb() {return b; }
~A() {cout<<"A destroyed"<<endl; }
};

class B :public A
{
public:
B(int m,int n):A(m,n) { cout<<"B created"<<endl;}
int geta() {return A::geta()*2; }
~B() {cout<<"B destroyed"<<endl; }
};

void main()
{
B b(2,2);
A* pa=&b;
b.geta();
pa->geta();
}
5. 源程序
#include<iostream.h>
#include<math.h>
#define pi 3.1416
class Point{
public:
Point(int a,int b)
{
x=a;
y=b;
}

int x;
int y;
};
class Object {
public:
virtual double calarea()=0;
virtual int IsIn(Point p)=0;
};

class Rect :public Object {
Point topleft;
Point bottomright;
public:
Rect(Point p1,Point p2): topleft(p1),bottomright(p2) {}
double calarea() {
return fabs((topleft.x-bottomright.x)* (topleft.y-bottomright.y));
}
int IsIn(Point p) {
if ((p.x>=topleft.x&&p.x<=bottomright.x)&&(p.y>=topleft.y&&p.y<=bottomright.y) )
return 1;
else return 0;
}
};

class Circle :public Object {
Point cc;
double radius;
public:
Circle(Point p,double r):cc(p),radius(r) {}
double calarea() {
return pi*radius*radius;
}
int IsIn(Point p) {
if ((p.x-cc.x)*(p.x-cc.x)+ (p.y-cc.y)* (p.y-cc.y)<radius*radius)
return 1;
else return 0;
}
};

void main()
{
Object *obj[2];
obj[0]=new Rect(Point(0,0),Point(100,200));
obj[1]=new Circle(Point(100,200),100.0);
int i;
for (i=0;i<2;i++) {
cout<<"the area is "<<obj[i]->calarea()<<endl;
}
}