#includeiostream using namespace std; templatetypename T class Person private T age; public void myswapT &a T&b T temp = a; a = b; b = temp; void
要修改代码才能输出正确的结果,需要在Person类中调用myswap函数来交换age的值,并在main函数中添加代码来调用myswap函数。修改后的代码如下:
#include<iostream>
using namespace std;
template<typename T>
class Person{
private:
T age;
public:
void myswap(T &a, T&b){
T temp = a;
a = b;
b = temp;
}
void show(){
cout << age << endl; // 输出年龄
}
};
int main(){
Person<int> max;
max.age = 30; // 设置年龄
max.show(); // 输出年龄
int a = 10;
int b = 20;
max.myswap(a, b); // 调用myswap函数来交换a和b的值
cout << a << " " << b << endl; // 输出交换后的a和b的值
}
修改后的代码会输出以下结果:
30
20 10
其中,第一行输出为设置的年龄值,第二行输出为交换后的a和b的值
原文地址: https://www.cveoy.top/t/topic/iVrB 著作权归作者所有。请勿转载和采集!