55 lines
1.1 KiB
C++
55 lines
1.1 KiB
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;
|
|
}
|
|
};
|
|
|
|
// 类模版作为函数参数
|
|
// 将类模版作为函数参数,可以将类模版的数据类型泛化
|
|
template <typename T>
|
|
void drawShape(Rectangle<T> &r)
|
|
{
|
|
r.draw();
|
|
r.length();
|
|
}
|
|
|
|
int main()
|
|
{
|
|
cout << "r1: " << endl;
|
|
Rectangle<int> r1(10, 20);
|
|
drawShape<int>(r1); // 显式指定模版参数
|
|
|
|
cout << "r2: " << endl;
|
|
Rectangle<double> r2(10.53, 20.25);
|
|
drawShape<>(r2); // 空<>表示自动推导
|
|
|
|
cout << "r3: " << endl;
|
|
Rectangle<float> r3(10.2f, 20.2f);
|
|
drawShape(r3); // 表示自动推导
|
|
|
|
return 0;
|
|
} |