鍍金池/ 問答/C++/ 編制求兩個(gè)數(shù)據(jù)中的最大值的函數(shù)模版程序

編制求兩個(gè)數(shù)據(jù)中的最大值的函數(shù)模版程序

1.編制求兩個(gè)數(shù)據(jù)中的最大值的函數(shù)模版程序;
2.源碼如下:

test.cpp

#include <iostream>
using namespace std;

template <class T>
T max(T m1, T m2)
{return (m1 > m2)? m1:m2;}

int main() {
    cout << max(2, 5) << "\t" << max(2.0, 5.) << "\t"
         << max('w', 'a') << "\t" << max("ABC", "ABD") << endl;

    return 0;
}

3.g++ test.cpp 時(shí)出現(xiàn):

test.cpp: 在函數(shù)‘int main()’中:
test.cpp:9:21: 錯(cuò)誤:調(diào)用重載的‘max(int, int)’有歧義
cout << max(2, 5) << "t" << max(2.0, 5.) << "t"

這是照書上敲的, 不知道是哪里出了問題, 求指教;

回答
編輯回答
萌吟

因?yàn)樵诿臻gstd中已經(jīng)有了一個(gè)max函數(shù),編譯器無法判斷你在調(diào)用哪個(gè)max函數(shù)。做出如下修改即可。

// test.cpp

#include <iostream>
//using namespace std;

template <class T>
T max(T m1, T m2)
{return (m1 > m2)? m1:m2;}

int main() {
    std::cout << max(2, 5) << "\t" << max(2.0, 5.) << "\t"
         << max('w', 'a') << "\t" << max("ABC", "ABD") << std::endl;

    return 0;
}
2017年3月3日 13:20