我正在编写模板类,特别是在数组中存储另一个模板类的模板类。我在设置配对成员 thing1 和 thing2 时遇到了麻烦。它们被打印为垃圾变量。
#ifndef ARRAY_H
#define ARRAY_H
#include"Pair.h"
#include<iostream>
using namespace std;
template<typename T>
class Array
{
template<typename U>
friend ostream & operator<<(ostream & out, const Array<U> &a);
private:
int size;
T* tPtr;
public:
Array(int s);
Array();
~Array();
T& operator[](int sub);
T operator[](int sub)const;
const Array<T> &operator =(const Array<T> &);
int getLength(){return size;};
};
template<typename T>
Array<T>::Array():size(0),tPtr(NULL)
{
}
template<typename T>
Array<T>::Array(int s):size(s)
{
tPtr = new T [size];
}
template<typename T>
Array<T>::~Array()
{
delete [] tPtr;
}
template<typename T>
T& Array<T>::operator[](int sub)
{
if(sub<0 || sub>size)
throw out_of_range("subscript out of range");
return tPtr[sub];
}
template<typename T>
T Array<T>::operator[](int sub)const
{
if(sub<0 || sub>size)
throw out_of_range("subscript out of range");
return tPtr[sub];
}
template<typename T>
const Array<T> &Array<T>::operator =(const Array<T> &right)
{
if(&right !=this)
{
if(size!=right.size)
{
delete [] tPtr;
size=right.size;
tPtr= new T[size];
}
for(int i =0;i<size;i++)
tPtr[i] = right.tPtr[i];
}
return *this;
}
template<typename U>
ostream & operator<<(ostream &out, const Array<U> &a)
{
for(int i =0;i<a.size;i++)
{
out<<a.tPtr[i];
}
out<<endl;
return out;
}
#endif
#ifndef PAIR_H
#define PAIR_H
#include <iostream>
using namespace std;
template<typename T,typename U>
class Pair {
private:
T thing1;
U thing2;
public:
Pair(){};
Pair( T thing1, U thing2) : thing1(thing1), thing2(thing2) {}
ostream & display(ostream & out=cout) const;
};
template<typename T,typename U>
ostream & Pair<T, U>::display(ostream & out) const {
return (out << "(" << thing1 << ", " << thing2 << ")");
}
template<typename T,typename U>
ostream & operator<<(ostream & out, const Pair<T,U> & pair) {
return pair.display(out);
}
#endif
#include "Pair.h"
#include "Array.h"
#include<string>
#include<iostream>
using namespace std;
template<typename T, typename U>
Array< Pair<T, U> >zip(Array<T> & lhs,Array<U> & rhs)
{
int zipLen = (lhs.getLength() < rhs.getLength() ? lhs.getLength() : rhs.getLength());
Array< Pair<T, U> >zipped(zipLen);
for (int i=0; i<zipLen; i++)
zipped[i] = Pair<T, U>(lhs[i], rhs[i]);
return zipped;//return array object
}
int main()
{
Array<int> a1(5);
Array<char>a2(3);
Array<Pair<int,char>>a3;
for(int i =1;i<5;i++)
a1[i-1]=i;
for(char ch='a';ch<='c';ch++)
a2[ch-'a']=ch;
a3=zip(a1,a2);//this is the line where I seem to lose all my data
cout<<a3;
system("pause");
return 0;
}