定义一个基类shape,再次基础上派生出 长方形,正方形,圆形,二者都有getArea()计算对象的面积

定义一个基类shape,再次基础上派生出 长方形,正方形,圆形,二者都有getArea()计算对象的面积


#include <iostream>
using namespace std;

//基类 shape
class Shape {
public:
	Shape() {}
	~Shape() {}
	virtual float getArea() {
		return -1;
	}
};

//派生类 圆形
class Circle :public Shape {
public:
	Circle(float radius):itsRadius(radius){}
	~Circle(){}
	float getArea() {
		return 3.14 * itsRadius * itsRadius;
	}
private:
	float itsRadius;
};


//派生类 长方形
class Rectangle :public Shape {
public:
	Rectangle(float len, float width) :itsLength(len), itsWidth(width) {};
	~Rectangle(){}
	virtual float getArea() {
		return itsLength * itsWidth;
	}
	virtual float getLength() {
		return itsLength;
	}
	virtual float getWidth() {
		return itsWidth;
	}
private:
	float itsWidth;
	float itsLength;
};

//正方形
class Square :public Rectangle {
public: 
	Square(float len);
	~Square() {}
};

Square::Square(float len) :Rectangle(len, len) {

}

int main() {
	Shape* sp;

	sp = new Circle(5);
	cout << "圆形的面积:" << sp->getArea() << endl;
	delete sp;
	sp = new Rectangle(4, 6);
	cout << "长方形的面积:" << sp->getArea() << endl;
	delete sp;
	sp = new Square(5);
	cout << "正方形的面积:" << sp->getArea() << endl;
	delete sp;
	return 0;
}

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,这是一个经典的面向对象编程问题。以下是一个可能的解决方案: ```c++ #include <iostream> using namespace std; class Shape { public: virtual double getArea() = 0; // 纯虚函数,用于计算面积 }; class Rectangle : public Shape { public: Rectangle(double w, double h) : width(w), height(h) {} double getArea() { return width * height; } private: double width; double height; }; class Trapezoid : public Shape { public: Trapezoid(double a, double b, double h) : top(a), bottom(b), height(h) {} double getArea() { return (top + bottom) * height / 2; } private: double top; double bottom; double height; }; class Circle : public Shape { public: Circle(double r) : radius(r) {} double getArea() { return 3.1415926 * radius * radius; } private: double radius; }; int main() { Shape* s1 = new Rectangle(3, 4); Shape* s2 = new Trapezoid(2, 4, 3); Shape* s3 = new Circle(5); cout << "Rectangle area: " << s1->getArea() << endl; cout << "Trapezoid area: " << s2->getArea() << endl; cout << "Circle area: " << s3->getArea() << endl; delete s1; delete s2; delete s3; return 0; } ``` 这个程序定义了一个抽象类 Shape,其中包含一个纯虚函数 getArea(),用于计算面积。然后从 Shape 派生三个具体的类:Rectangle、Trapezoid 和 Circle,分别用于计算长方形、梯形和圆形面积。在 main 函数中,我们通过类指针来调用派生类中的虚函数,计算不同形状的面积。 希望这个解决方案能够帮助你理解如何定义抽象类和派生类,以及如何使用虚函数来实现多态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Roam-G

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值