qfedu-cpp-level/day7/d5.cpp

47 lines
806 B
C++
Raw Permalink Normal View History

2023-08-01 18:51:53 +08:00
// 类模版派生普通类
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
template <typename T>
class Shape
{
protected:
T iPerimeter;
public:
// virtual double area() = 0;
virtual T perimeter() { return iPerimeter; } // 周长
};
class Rectangle : public Shape<int>
{
private:
int width, height;
public:
Rectangle(int w, int h) : width(w), height(h) { iPerimeter = 2 * (w + h); }
};
class Triangle : public Shape<float>
{
private:
float a, b, c;
public:
Triangle(float a, float b, float c) : a(a), b(b), c(c) { iPerimeter = a + b + c; }
};
int main()
{
Rectangle r1(10, 20);
cout << "r1周长: " << r1.perimeter() << endl;
Triangle t1(3.0f, 4.0f, 5.0f);
cout << "t1周长: " << t1.perimeter() << endl;
return 0;
}