模板

#include<iostream>

using namespace std;

template <class T>

sum(T* array, int size = 0)

{

total = 0;

for (int i = 0; i < size; i++)

total += array[i];

return total;

}

 

template <class T1, class T2>

T2 sum(T1* array1, T2* array2, int size = 0)

{

T2 total = 0;

for (int i = 0; i < size; i++)

total += array1[i] + array2[i];

return total;

}

 

char* sum(char* s1, char* s2)

{

char* str = new char[strlen(s1) + strlen(s2)];

strcpy(str, s1);

return strcat(str, s2);

}

void main()

{

int iArr[] = { 1,2,3,4,5 };

double dArr[] = { 1.1,2.2,3.3,4.4,5.5 };

char* p1 = "Hello,";

char* p2 = "World";

int iTotal = sum(iArr, 5);

double dTotal = sum(dArr, 5);

double idTotal = sum(iArr, dArr, 5);

p1 = sum(p1, p2);

cout << iTotal << endl;

cout << dTotal << endl;

cout << idTotal << endl;

cout << p1 << endl;

}

 

 

#include<iostream>

using namespace std;

template <class T,int n>

class mysequence {

memblock[N];

public:

void setmember(int x, T value)

{

memblock[x] = value;

 

}

getmember(int x) {

return memblock[x];

}

};

 

int main()

{

mysequence<int, 5>myints;

mysequence<double, 5>myfloats;

myints.setmember(0, 100);

myfloats.setmember(3, 3.1416);

cout << myints.getmember(0) << endl;

cout << myfloats.getmember(3) << endl;

return 0;

}

posted @ 2023-05-11 21:58  平安喜乐×  阅读(15)  评论(0)    收藏  举报