注册 登录
编程论坛 C++教室

[求助]关于派生

王崇 发布于 2006-12-26 22:37, 532 次点击
定义一个Shape抽象类,在此基础上派生出Rectangle和Circle,二者都有GetArea()函数计算对象的面积,GetPerim()函数计算对象的周长。
4 回复
#2
lrgsz2006-12-26 23:51
怎么了,Sharp不能定义对象,Rentangle和Circle是从Sharp派生出来的类,是具体的类可以定义自己的对象!
#3
dragonfly2006-12-27 08:49
Shape 类定义虚函数
virtual GetArea()
virtual GetPerim()
在派生类中,定义各自的GetArea()和GetPerim()
#4
王崇2006-12-27 09:09

#include<iostream.h>

#include<math.h>

class shape

{ public:

virtual void getarea()=0;

virtual void getperim()=0;

};

class rectangle:public shape

{ int a,b,c;

double s,p;

public:

rectangle(int a1,int b1,int c1) {a=a1;b=b1;c=c1;}

void getperim()

{ p=a+b+c; cout<<"周长 "<<p<<endl;}

void getarea()

{ p=(a+b+c)/2.0;

s=sqrt(p*(p-a)*(p-b)*(p-c));

cout<<"面积 "<<s<<endl;

}

};

class circle :public shape

{ float r,s,p;

public:

circle(float r1) {r=r1;}

void getperim() { p=2*r*3.1415926;cout<<"周长 "<<p<<endl;}

void getarea() { s=r*r*3.1415926; cout<<"面积 "<<s<<endl;}

};

void show(shape *p)

{ p->getarea();

p->getperim();

}

void main()

{ shape *p;

rectangle a(3,4,5);

circle b(10);

p=&a; show(p);

p=&b; show(p);

}
我做的对么???

#5
pusawl2006-12-27 13:53
正确,不过注意书写格式
1