创建类模板AofP,保证下面的主函数正常执行 template<class T1, class T2> class AofP { T1 p1,p2; T2 p3; …} template<class T2> class AofP<int, T2> { …} int main() { AofP<int, int> arr1(20,30,5); cout<<arr1.p1p2len(); }
时间: 2023-12-20 18:03:30 浏览: 16
可以这样实现AofP类模板:
```cpp
#include <iostream>
using namespace std;
template<class T1, class T2>
class AofP {
public:
AofP(T1 p1, T1 p2, T2 p3) {
this->p1 = p1;
this->p2 = p2;
this->p3 = p3;
}
int p1p2len() {
return p2 - p1;
}
private:
T1 p1, p2;
T2 p3;
};
template<class T2>
class AofP<int, T2> {
public:
AofP(int p1, int p2, T2 p3) {
this->p1 = p1;
this->p2 = p2;
this->p3 = p3;
}
int p1p2len() {
return p2 - p1;
}
private:
int p1, p2;
T2 p3;
};
int main() {
AofP<int, int> arr1(20, 30, 5);
cout << arr1.p1p2len() << endl; // 输出10
return 0;
}
```
在上述代码中,我们定义了一个类模板 `AofP`,它有两个模板参数 `T1` 和 `T2`,还有三个成员变量 `p1`、`p2` 和 `p3`。其中,`p1` 和 `p2` 的类型为 `T1`,`p3` 的类型为 `T2`。我们还定义了一个成员函数 `p1p2len()`,它返回 `p2 - p1` 的值。
接着,我们对 `AofP` 类模板进行了偏特化,当 `T1` 为 `int` 时,使用 `int` 类型的 `p1` 和 `p2` 成员变量。在 `main()` 函数中,我们创建了一个 `AofP<int, int>` 类型的对象 `arr1`,它的 `p1` 值为 `20`,`p2` 值为 `30`,`p3` 值为 `5`。最后,我们输出 `arr1` 的 `p1p2len()` 值,即 `10`。