2. 以下程序使用类模板定义了Pair类。程序的输出结果为:100。请改正程序中的4处错误。 1 #include <iostream> 2 using namespace std; 3 4 template<T>**** 5 class Pair { 6 public: 7 Pair(T val_1, T val_2) { 8 value1 = val_1; 9 value2 = val_2; 10 } 11 void getmax(); 12 private: 13 T value1, value2; 14 }; 15 16 template<class T> 17 T Pair<T>::getmax() { 18 int value; 19 value = value1 > value2 ? value1 : value2;*** 20 return value; 21 } 22 23 int main() { 24 template<int>Pair pa(100, 75); 25 cout << pa.getmax() << endl; 26 27 return 0; 28 }
时间: 2024-03-09 16:49:42 浏览: 70
以下是修改后的程序:
```
#include <iostream>
using namespace std;
template<class T>
class Pair {
public:
Pair(T val_1, T val_2) {
value1 = val_1;
value2 = val_2;
}
T getmax();
private:
T value1, value2;
};
template<class T>
T Pair<T>::getmax() {
T value;
value = value1 > value2 ? value1 : value2;
return value;
}
int main() {
Pair<int> pa(100, 75);
cout << pa.getmax() << endl;
return 0;
}
```
修改的部分包括:
1. 在类模板的定义中,需要使用 `template<class T>` 或 `template<typename T>` 来声明模板参数类型。
2. 在类模板的定义中,函数 `getmax()` 的返回类型应该为模板参数类型 `T`。
3. 在类模板的定义中,需要在函数 `getmax()` 的前面加上 `template<class T>` 或 `template<typename T>` 来声明该函数使用模板参数类型。
4. 在 `main()` 函数中,需要通过 `Pair<int>` 明确指定模板参数类型为 `int`。
阅读全文
相关推荐
















