Hi there fellow computer scientists, I'm having a lot of issues with my code, everything works except for the friend ostream& operator function. I keep getting a compiler error when sending my class object to cout. I'm thinking a made an error while declaring the friend function or maybe within its declaration.Here is the code:
By the way I know its traditional to use T for templates but I used my professors name, it sounds weird but using unconventional names in my code helps me remember programming concepts like templates and etc
#include <iostream>
#include <cstdlib>
using namespace std;
template <class Chris>
class DynamicArray{
private:
Chris *myArray;
int capacity;
int num_items;
public:
DynamicArray();
DynamicArray(int initialCapacity);
void reSize(int newCapacity);
void addElement(const Chris element);
Chris& operator[](int index)const;
friend std::ostream& operator << (std::ostream& outputStream, const
DynamicArray<Chris>& obj);
virtual ~DynamicArray();
};
int main(){
DynamicArray<int> Array(20);
Array.addElement(20);
Array.addElement(12);
Array.addElement(13);
Array.addElement(45);
Array.addElement(78);
cout<<Array<<endl;
return 0;
}
template<class Chris>
ostream& operator<< (ostream& outputStream, const DynamicArray<Chris>&
obj)
{
for(int index=0; index<obj.num_items; index++){
if(index<(obj.num_items-1)){
outputStream<<obj.myArray[index]<<",";
}
else{
outputStream<<obj.myArray[index];
}
}
return outputStream;
}
template<class Chris>
DynamicArray<Chris>::DynamicArray():capacity(1),num_items(0)
{
myArray=new Chris[capacity];
}
template <class Chris>
DynamicArray<Chris>::DynamicArray(int initialCapacity):num_items(0)
{
if(initialCapacity>0){
capacity=initialCapacity;
myArray=new Chris[capacity];
}
else{
cout<<"ERROR, capacity cannot be negative or 0 " <<endl;
exit(0);
}
}
template <class Chris>
void DynamicArray<Chris>::reSize(int newCapacity)
{
if(newCapacity<=capacity){
cout<<"ERROR, the new capacity must be greater than the current
capacity"<<endl;
exit(1);
}
Chris *biggerArray = new Chris[newCapacity];
for(int index=0; index<num_items; index++){
biggerArray[index]=myArray[index];
}
delete [] myArray;
capacity=newCapacity;
myArray= new Chris[capacity];
for(int index=0; index<num_items; index++){
myArray[index]= biggerArray[index];
}
delete [] biggerArray;
}
template <class Chris>
Chris& DynamicArray<Chris>::operator [](int index)const
{
if(index>=num_items){
cout<<"ERROR,ARRAYINDEX OUT OF BOUNDS " <<endl;
exit(0);
}
return myArray[index];
}
template<class Chris>
void DynamicArray<Chris>::addElement(const Chris element){
if(num_items==capacity){
reSize(capacity*2);
}
myArray[num_items]=element;
num_items++;
}
template<class Chris>
DynamicArray<Chris>::~DynamicArray()
{
delete [] myArray;
}
The compiler error is :undefined reference ,also it states that my friend ostream& function was not declared as a template. I have to idea how to fix this