注册 登录
编程论坛 C++教室

c++ primer plus 第八章练习题的第六题

迷途的菜鸟 发布于 2012-12-15 16:26, 375 次点击
程序代码:
#include <iostream>
#include <cstring>
using namespace std;
template <class T>
T maxn(T arr[], int n)
{
    T max = arr[0];
    for (int i = 0; i < n; ++i)
    {
        if (arr[i] > max)
        {
            max = arr[i];
        }
    }
    return max;
}
template <> char* maxn<char*>(char* pa[], int n)
{
    int MaxLen = strlen(pa[0]);
    for (int i = 0; i < n; ++i)
    {
        if (strlen(pa[i]) > MaxLen)
        {
            MaxLen = strlen(pa[i]);
        }
    }
    return pa[i];
}

int main(void)
{
    int test[3] = {1,2,4};
    double dtest[3] = {1.1,2.2, 3};
    char* ptest[3] = {"first blood", "double kill", "triple kill"};
    cout << "func1 :" << maxn(test,3) << endl;
    cout << "func2 :" << maxn(dtest,3) << endl;
    cout << "func3 :" << maxn(ptest,3) << endl;

    return 0;
}


用模板和具体化,程序崩溃,不知为啥,请求帮助!
1 回复
#2
chenhm19912012-12-15 22:54
return pa[i];这个句子里的i是不是已经越界了呢~问题就出在这儿!
1