C++ template

来源:百度知道 编辑:UC知道 时间:2024/06/28 21:37:48
我用的是VC++ 6.0

#include <iostream>
using namespace std;
template <typename T>
void ShowArray(T arr[], int n);

template <typename T>
void ShowArray(T * arr[], int n);

struct debts
{
char name[50];
double amount;
};

int main(void)
{
int things[6] = { 13, 31, 103, 301, 310, 130} ;
struct debts mr_E[3] =
{
{"Ima Wolfe", 2400.0} ,
{"Ura Foxe ", 1300.0} ,
{"Iby Stout", 1800.0}
};
double * pd[3];

for (int i = 0; i < 3; i++)
pd[i] = &mr_E[i].amount;

cout << "Listing Mr. E's counts of things:\n";
ShowArray(things, 6);
cout << "Listing Mr. E's debts:\n";
ShowArray(pd, 3); // 这行有错
system("pause");

把错误的行改成ShowArray<double>(pd, 3);
现在来分析一下为什么你的程序会有问题。
double * pd[3];
ShowArray(pd, 3); 这句话 有两种解释。
第一种是你想象的那种,调用下面这个模板函数:
template <typename T>
void ShowArray(T * arr[], int n);

但是同时double* pd[3]有可以看是int pd[3]。因为指针的值本身就是以个int型的值,而这个值代表的是指针所指向的内存地址。你不妨可以试一下,去掉
template <typename T>
void ShowArray(T arr[], int n);
这个模板函数的定义,运行你的程序。

// 888.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;
template <typename T>
void ShowArray(T arr[], int n)
{
cout << "template A\n";
for (int i = 0; i < n; i++)
cout << arr[i] << ' ';
cout << endl;
}

template <typename T>
void Show888(T* arr[], int n)
{
cout << "template B\n&qu