48 lines
1.2 KiB
C++
48 lines
1.2 KiB
C++
// 类模版类内部实现
|
|
// 在类模版内部的成员函数中,可以使用泛型成员变量
|
|
#include <iostream>
|
|
#include <cstring>
|
|
#include <cstdlib>
|
|
#include <cmath> // sqrt
|
|
|
|
using namespace std;
|
|
|
|
template <typename T1, typename T2>
|
|
class Point
|
|
{
|
|
private:
|
|
T1 x;
|
|
T2 y;
|
|
|
|
public:
|
|
Point(T1 x, T2 y) : x(x), y(y) {}
|
|
|
|
public:
|
|
// ? T1, T2 是哪一个对象的泛型的具体化?是当前调用的对象的泛型
|
|
// 此函数要求两个对象的泛型必须一致
|
|
float distance(Point<T1, T2> &other)
|
|
{
|
|
return sqrt((this->x - other.x) * (this->x - other.x) + (this->y - other.y) * (this->y - other.y));
|
|
}
|
|
};
|
|
|
|
int main()
|
|
{
|
|
// 类的泛型必须指定类型
|
|
Point<float, float> p1(2, 3);
|
|
Point<float, float> p2(4, 5.5f);
|
|
cout << "p1和p2的距离: " << p1.distance(p2) << endl;
|
|
|
|
Point<int, int> p3(2, 3);
|
|
Point<int, int> p4(4, 5.5f);
|
|
cout << "p3和p4的距离: " << p3.distance(p4) << endl;
|
|
|
|
// 只有同类型的对象才能调用成员函数
|
|
// 调用成员函数时,泛型的具体化是当前调用的对象的泛型
|
|
Point<int, float> p5(2, 3);
|
|
Point<int, float> p6(4, 5.5f);
|
|
cout << "p5和p6的距离: " << p5.distance(p6) << endl;
|
|
|
|
return 0;
|
|
}
|