qfedu-cpp-level/day6/homework/h6.cpp

56 lines
989 B
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其中包含一个纯虚函数 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;
}