53 lines
1007 B
C++
53 lines
1007 B
C++
// 类模版
|
|
// 类模版是成员变量的数据类型泛化
|
|
// 类模版的声明作用于整个类,而不是单个成员,即类的内部的任何位置都可以使用
|
|
|
|
// 如: 定义长方形的图形类
|
|
|
|
#include <iostream>
|
|
#include <cstring>
|
|
#include <cstdlib>
|
|
|
|
using namespace std;
|
|
|
|
// 类模版
|
|
template <typename T>
|
|
class Rectangle
|
|
{
|
|
private:
|
|
T width, height; //矩形的宽和高
|
|
|
|
public:
|
|
Rectangle(T w, T h) : width(w), height(h) {}
|
|
|
|
public:
|
|
void draw()
|
|
{
|
|
cout << "绘制矩形"
|
|
<< "宽: " << width << "高: " << height << endl;
|
|
}
|
|
void length()
|
|
{
|
|
cout << "矩形周长: " << 2 * (width + height) << endl;
|
|
}
|
|
};
|
|
|
|
int main()
|
|
{
|
|
cout << "r1: " << endl;
|
|
Rectangle<int> r1(10, 20);
|
|
r1.draw();
|
|
r1.length();
|
|
|
|
cout << "r2: " << endl;
|
|
Rectangle<double> r2(10.53, 20.25);
|
|
r2.draw();
|
|
r2.length();
|
|
|
|
cout << "r3: " << endl;
|
|
Rectangle<float> r3(10.2f, 20.2f);
|
|
r3.draw();
|
|
r3.length();
|
|
|
|
return 0;
|
|
} |