第16周上機實踐項目3——max帶來的衝突,第16周max
分析下面程式出現的編譯錯誤,給出解決的方案。
#include<iostream>using namespace std;//定義函數模板template<class T>T max(T a, T b){ return (a>b)?a:b;}int main(){ int x=2,y=6; double x1=9.123,y1=12.6543; cout<<"把T執行個體化為int:"<<max(x,y)<<endl; cout<<"把T執行個體化為double:"<<max(x1,y1)<<endl; return 0;}
其實C++中有了一個標準的max函數,經過一年多的學習也知道了這一點,每次打出max的時候,codeblocks就會給出補充,這明顯是已經定義過了的,所以解決方案有一下幾種
1、在max前加std::,代表使用標準庫中的max
#include<iostream>using namespace std;//定義函數模板template<class T>T max(T a, T b){ return (a>b)?a:b;}int main(){ int x=2,y=6; double x1=9.123,y1=12.6543; cout<<"把T執行個體化為int:"<<std::max(x,y)<<endl; cout<<"把T執行個體化為double:"<<std::max(x1,y1)<<endl; return 0;}
2、在max前加::,代表使用當前定義的max
#include<iostream>using namespace std;//定義函數模板template<class T>T max(T a, T b){ return (a>b)?a:b;}int main(){ int x=2,y=6; double x1=9.123,y1=12.6543; cout<<"把T執行個體化為int:"<<::max(x,y)<<endl; cout<<"把T執行個體化為double:"<<::max(x1,y1)<<endl; return 0;}
3、把using namespace std改成using std::cout;using std::endl,代表只使用標準庫中的cout和endl
#include<iostream>using std::cout;using std::endl;//定義函數模板template<class T>T max(T a, T b){ return (a>b)?a:b;}int main(){ int x=2,y=6; double x1=9.123,y1=12.6543; cout<<"把T執行個體化為int:"<<max(x,y)<<endl; cout<<"把T執行個體化為double:"<<max(x1,y1)<<endl; return 0;}