亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

以下內容是關于C語言函數模板問題,為什么報錯呢?

以下內容是關于C語言函數模板問題,為什么報錯呢?

C PHP
qq_遁去的一_1 2021-12-02 20:07:59
#include "stdafx.h"#include <iostream>template <class T>void swap(T &a,T &b);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;}void swap(T &a,T &b){int temp;temp=a;a=b;b=temp;}為什么報錯呢?
查看完整描述

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改個名字。

查看完整回答
反對 回復 2021-12-07
?
蝴蝶不菲

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;
}



查看完整回答
反對 回復 2021-12-07
?
神不在的星期二

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;
}



查看完整回答
反對 回復 2021-12-07
  • 3 回答
  • 0 關注
  • 384 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號