定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square
#include
#define pi 3.14
using namespace std;
class Shape{
public:
virtual float getArea(){return 0;}
virtual ~Shape(){}
};
class Rectangle:public Shape{
private:
int lenth,width;
public:
Rectangle(int len,int wid):lenth(len),width(wid){}
float getArea(){return width*lenth;}
};
class Circle:public Shape{
private:
int r;
public:
Circle(int r1):r(r1){}
float getArea(){return pi*r*r;}
};
int main()
{
int a,b,r;
cout<<"Input a,b:";
cin>>a>>b;
cout<<"Input r:";
cin>>r;
Shape *ps;
ps=new Rectangle(a,b);
Shape *pr;
pr=new Circle(r);
cout<<"Rectangle Area:"<<ps->getArea()<<","<<"Circle Area:"<<pr->getArea()<<endl;
delete ps;
delete pr;
return 0;
}
为什么这个派生类square在这个中并没有体现出来,这和题目相符吗?
派生类square我怎么没看到这个
class Square : public Rectangle
{
}
你说的对,这个没有按照题意
需加上
class Square : public Rectangle
{
public Square(int x): Rectangle(x, x) {}
};
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def getArea(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def getArea(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def getArea(self):
return 3.14159 * self.radius * self.radius
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
rectangle = Rectangle(5, 3)
circle = Circle(4)
square = Square(5)
print(rectangle.getArea()) # 输出: 15
print(circle.getArea()) # 输出: 50.26544
print(square.getArea()) # 输出: 25
如果题目中并未体现Square类的功能,可能是因为题目只是简要介绍了继承关系,并未详细说明派生类Square的用途。但是根据题目要求,我们按照正常流程创建了Square类,并在代码示例中展示了它的使用。