56 lines
989 B
C++
56 lines
989 B
C++
|
// 创建一个基类 Shape,其中包含一个纯虚函数 perimeter() ,用于计算形状的周长。从 Shape 派生出 Triangle 类和 Square 类,分别实现计算三角形和正方形的周长的函数。
|
|||
|
#include <iostream>
|
|||
|
#include <cstring>
|
|||
|
#include <cstdlib>
|
|||
|
|
|||
|
using namespace std;
|
|||
|
|
|||
|
class Shape
|
|||
|
{
|
|||
|
public:
|
|||
|
// 用于计算形状的周长
|
|||
|
virtual double perimeter() = 0;
|
|||
|
};
|
|||
|
|
|||
|
class Triangle : public Shape
|
|||
|
{
|
|||
|
private:
|
|||
|
double a, b, c;
|
|||
|
|
|||
|
public:
|
|||
|
Triangle(double a, double b, double c) : a(a), b(b), c(c) {}
|
|||
|
|
|||
|
public:
|
|||
|
double perimeter()
|
|||
|
{
|
|||
|
return a + b + c;
|
|||
|
}
|
|||
|
};
|
|||
|
|
|||
|
class Square : public Shape
|
|||
|
{
|
|||
|
private:
|
|||
|
double a;
|
|||
|
|
|||
|
public:
|
|||
|
Square(double a) : a(a) {}
|
|||
|
|
|||
|
public:
|
|||
|
double perimeter()
|
|||
|
{
|
|||
|
return 4 * a;
|
|||
|
}
|
|||
|
};
|
|||
|
|
|||
|
int main()
|
|||
|
{
|
|||
|
Shape *p = new Triangle(3, 4, 5);
|
|||
|
|
|||
|
cout << "三角形的周长是: " << p->perimeter() << endl;
|
|||
|
|
|||
|
p = new Square(5);
|
|||
|
|
|||
|
cout << "正方形的周长是: " << p->perimeter() << endl;
|
|||
|
return 0;
|
|||
|
}
|