3 回答

TA貢獻1820條經驗 獲得超10個贊
首先,C沒有函數模版。C++才有。
其次,template <class T>是函數聲明的一部分,所以下面函數實現應該是:
template <class T>
void swap(T &a,T &b){
int temp;
temp=a;
a=b;
b=temp;
}
最后,#include <iostream>,在標準的C++函數中,std的域中已經有一個swap函數。
而且前面也using namespace了。函數聲明重復。
兩個辦法:
1 swap(i,j);改為 ::swap(i,j); //全局化。
2 swap改個名字。

TA貢獻1810條經驗 獲得超4個贊
#include "stdafx.h"
#include <iostream>
template <class T>
void myswap(T &a,T &b); //因為標準模板庫中有swap函數,系統不能識別,我只要函數名改一下就可以了
int main(){
using namespace std;
int i=20;
int j=30;
cout<<"i,j="<<i<<j<<endl;
swap(i,j);
cout<<i<<","<<j<<endl;
getchar();
return 0;
}
template <class T> //這里也需要
void myswap(T &a,T &b){
T temp;
temp=a;
a=b;
b=temp;
}

TA貢獻1963條經驗 獲得超6個贊
#include <iostream>
using namespace std; //引入std命名空間
template <class T>
void myswap(T &a,T &b); //swap在iostream定義過了,換個名字
int main(){
using namespace std;
int i=20;
int j=30;
cout<<"i,j="<<i<<j<<endl;
myswap(i,j);
cout<<i<<","<<j<<endl;
getchar();
return 0;
}
template<class T> //這個還是要寫一遍
void myswap(T &a,T &b){
T temp; //temp是T類型
temp=a;
a=b;
b=temp;
}
- 3 回答
- 0 關注
- 384 瀏覽
添加回答
舉報