第16周上機實踐項目3——max帶來的衝突,第16周max

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.