[Dev-C++] non-template function friend to template class question
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Ioannis V. <jv...@at...> - 2000-09-19 20:46:24
|
I am currently studying C++, and these days templates. So here is some code:
#include <iostream.h>
const int DefaultSize=10;
class Animal
{
public:
Animal(int);
Animal();
~Animal() {}
int GetWeight() const { return itsWeight; }
void Display() const { cout<<itsWeight; }
private:
int itsWeight;
};
Animal::Animal(int weight): itsWeight(weight)
{}
Animal::Animal():itsWeight(0)
{}
template <class T>
class Array
{
public:
Array(int itsSize);
Array(const Array &rhs);
~Array() { delete[] pType; }
Array &operator=(const Array &);
T &operator[](int offSet) { return pType[offSet]; }
const T &operator[](int offSet) const { return pType[offSet]; }
int GetSize() const { return itsSize; }
friend void Intrude(Array<int>);
private:
T *pType;
int itsSize;
};
template <class T>
Array<T>::Array(int size=DefaultSize):itsSize(size)
{
pType=new T[size];
for(int i=0; i<size; i++)
pType[i]=0;
}
template <class T>
Array<T>::Array(const Array &rhs)
{
itsSize=rhs.GetSize();
pType=new T[itsSize];
for(int i=0; i<itsSize; i++)
pType[i]=rhs[i];
}
template <class T>
Array<T> & Array<T>::operator=(const Array &rhs)
{
if(this==&rhs)
return *this;
delete[] pType;
itsSize=rhs.GetSize();
pType=new T[itsSize];
for(int i=0; i<itsSize; i++)
pType[i]=rhs[i];
return *this;
}
void Intrude(Array<int> theArray)
{
cout<<"\n*** Intrude ***\n";
for(int i=0; i<theArray.itsSize; i++)
cout<<"i: "<<theArray.pType[i]<<endl;
cout<<"\n";
}
int main()
{
Array<int> theArray;
Array<Animal> theZoo;
Animal *pAnimal;
for(int i=0; i<theArray.GetSize(); i++)
{
theArray[i]=i*2;
pAnimal=new Animal(i*3);
theZoo[i]=*pAnimal;
}
int j, k;
for (j=0; j<theArray.GetSize(); j++)
{
cout<<"theZoo["<<j<<"]:\t";
theZoo[j].Display();
cout<<endl;
}
Intrude(theArray);
for(k=0; k<theArray.GetSize(); k++)
delete &theZoo[j];
cout<<"\n\nDone.\n";
return 0;
}
Here is the result of the compiler:
Borland C++ 5.5 for Win32 Copyright (c) 1993, 2000 Borland
temp.cpp:
Error E2247 temp.cpp 77: 'Array<int>::itsSize' is not accessible in function
Intrude(Array<int>)
Error E2247 temp.cpp 78: 'Array<int>::pType' is not accessible in function
Intrude(Array<int>)
*** 2 errors in Compile ***
Why these errors occur. How can i declare a non template function as a
friend in
a template class? If someone knows and answers i 'll be grateful.
Ioannis
* Ioannis Vranos
* Programming pages: http://members.nbci.com/noicys
* Alternative URL: http://run.to/noicys
|