进行编程储存任意一组数据,类型可以使数字,字符,数组等任意类型,之后输出出来
必需用到这几个:模版和运算符重载
參考答案:是这个意思不?
#include <iostream>
using namespace std;
template<class T>
class AnyArray
{
public:
typedef unsigned int size_type;
AnyArray(){}
AnyArray(const T* t, size_type array_size) : ArraySize(array_size)
{
Array = new T[ArraySize];
for(size_type i = 0; i < ArraySize; ++i)
Array[i] = t[i];
}
void operator = (const AnyArray& Any)
{
this->ArraySize = Any.ArraySize;
this->Array = new T[Any.ArraySize];
for(size_type i = 0; i < Any.ArraySize; ++i)
this->Array[i] = Any.Array[i];
}
~AnyArray()
{
delete [] Array;
}
friend ostream& operator << (ostream& os, AnyArray& Any)
{
T* iterator = Any.Array;
for(size_type i = 0; i < Any.ArraySize; ++i, ++iterator)
os << *iterator << ' ';
os << endl;
return os;
}
private:
T* Array;
size_type ArraySize;
};
int main()
{
// 整形
int a[10];
for(int i = 0; i < sizeof a/sizeof a[0]; ++i)
a[i] = i + 1;
AnyArray<int> integer(a, sizeof a/sizeof a[0]);
cout << "integer: " << integer;
// 浮点
double b[10];
for(int i = 0; i < sizeof b/sizeof b[0]; ++i)
b[i] = (i + 1) * 1.11;
AnyArray<double> floating(b, sizeof b/sizeof b[0]);
cout << "floating: " << floating;
// 字符
char c[10];
for(int i = 0; i < sizeof c/sizeof c[0]; ++i)
c[i] = 'A' + i;
AnyArray<char> character(c, sizeof c/sizeof c[0]);
cout << "character: " << character << endl;
// 数组
char c1[10], c2[10], c3[10];
for(int i = 0; i < sizeof c1/sizeof c1[0]; ++i)
{
c1[i] = 'A' + i;
c2[i] = '!' + i;
c3[i] = '0' + i;
}
AnyArray<char> chars[3];
chars[0] = AnyArray<char>(c1, sizeof c1/sizeof c1[0]);
chars[1] = AnyArray<char>(c2, sizeof c2/sizeof c2[0]);
chars[2] = AnyArray<char>(c3, sizeof c3/sizeof c3[0]);
for(int i = 0; i < 3; ++i)
{
cout << "chars[" << i << "]: " << chars[i];
}
}
输出:
integer: 1 2 3 4 5 6 7 8 9 10
floating: 1.11 2.22 3.33 4.44 5.55 6.66 7.77 8.88 9.99 11.1
character: A B C D E F G H I J
chars[0]: A B C D E F G H I J
chars[1]: ! " # $ % & ' ( ) *
chars[2]: 0 1 2 3 4 5 6 7 8 9
请按任意键继续. . .