qfedu-cpp-level/day5/homework/h7.cpp

43 lines
1.1 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 假设有两个类Shape形状和 Rectangle矩形。Shape 类具有一个成员函数 getArea() 用于计算形状的面积。Rectangle 类继承自 Shape 类,并添加了两个成员变量 width宽度和 height高度。请在给定的类定义中完成代码并实现 Rectangle 类的 getArea() 函数来计算矩形的面积。
// 【提示】Shape的类设计如下表示为抽象类getArea() 是纯虚函数):
// class Shape
// {
// public:
// virtual double getArea() const = 0;
// };
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Shape
{
public:
virtual double getArea() const = 0;
};
class Rectangle : public Shape
{
private:
double width, height;
public:
Rectangle(double width, double height) : width(width), height(height) {}
~Rectangle() {}
public:
double getArea() const // 重写父类的纯虚函数const 可以保证不会修改成员变量的值
{
return width * height;
}
};
int main()
{
Shape *shape = new Rectangle(3, 4);
cout << shape->getArea() << endl; // 12
return 0;
}