38 lines
861 B
C++
38 lines
861 B
C++
|
// 类模版派生普通类
|
||
|
#include <iostream>
|
||
|
#include <cstring>
|
||
|
#include <cstdlib>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
template <typename T>
|
||
|
class Shape
|
||
|
{
|
||
|
public:
|
||
|
virtual T perimeter() = 0; // 周长
|
||
|
};
|
||
|
|
||
|
// 类模版派生类模版
|
||
|
// 派生的子类模版不能使用父类模版的成员变量,因为父类模版的成员变量是在编译时期确定的,而子类模版是在运行时期确定的
|
||
|
template <typename T>
|
||
|
class Rectangle : public Shape<T>
|
||
|
{
|
||
|
private:
|
||
|
T width, height;
|
||
|
|
||
|
public:
|
||
|
Rectangle(T w, T h) : width(w), height(h) {}
|
||
|
virtual T perimeter() { return 2 * (width + height); } // 周长
|
||
|
};
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
// 必须使用 int 来指定类型
|
||
|
Rectangle<int> r1(10, 20);
|
||
|
cout << "r1周长: " << r1.perimeter() << endl;
|
||
|
|
||
|
Rectangle<float> r2(10.2f, 20.2f);
|
||
|
cout << "r2周长: " << r2.perimeter() << endl;
|
||
|
return 0;
|
||
|
}
|