Basically in my driver.cpp, in my main method, I simply just for testing purposes, instantiate a object.
#include "SafeArray.h"
#include <iostream>
int main () {
SafeArray<int> a1(4);
return 0;
}
Basically no matter which constructor I use, I get the unresolved external symbol for the constructor and destructor.
All files in the same directory I did: g++ -c SafeArray.cpp g++ -o driver driver.cpp SafeArray.o
(linker errors)
And for VS and Xcode, i simply placed the files in their designated directory specified for header and source code, and when I build I get hit with the linker errors.
I have a feeling its something very simple im doing wrong, and I apologize in advance
Here's my header file:
#ifndef SAFE_ARRAY_H
#define SAFE_ARRAY_H
using namespace std;
template <class T>
class SafeArray {
private:
int low, high;
T* p;
public:
SafeArray();
SafeArray(int i);
SafeArray(int l, int h);
SafeArray(const SafeArray &s);
~SafeArray();
T& operator[](int i);
SafeArray<T>& operator=(const SafeArray<T>& s);
friend ostream& operator<<(ostream& os, SafeArray<T> s);
};
#endif
Here's my .cpp file:
#include "stdafx.h"
#include <iostream>
#include "SafeArray.h"
using namespace std;
template <class T>
SafeArray<T>::SafeArray() {
low = 0;
high = -1;
p = NULL;
}
template <class T>
SafeArray<T>::SafeArray(int i) {
low = 0;
high = i - 1;
p = new T[i];
}
template <class T>
SafeArray<T>::SafeArray(int l, int h) {
if ((h - l + 1) <= 0) {
cout << "Constructor error in bounds definition" << endl;
exit(1);
}
low = l;
high = h;
p = new T[h - l + 1];
}
template <class T>
SafeArray<T>::SafeArray(const SafeArray& s) {
int size = s.high - s.low + 1;
p = new T[size];
for (int i = 0; i < size; i++) {
p[i] = s.p[i];
}
low = s.low;
high = s.high;
}
template <class T>
SafeArray<T>::~SafeArray() {
delete[] p;
}
template <class T>
T& SafeArray<T>::operator[] (int i) {
if (i < low || i > high) {
cout << "index " << i << " out of bounds" << endl;
exit(1);
}
return p[i - low];
}
template <class T>
SafeArray<T>& SafeArray<T>::operator=(const SafeArray<T>& s) {
if (this == &s) {
return *this;
}
delete[] p;
int size = s.high - s.low + 1;
p = new T[size];
for (int i = 0; i < size; i++) {
p[i] = s.p[i];
}
low = s.low;
high = s.high;
return *this;
}
template <class T>
ostream& operator<<(ostream& os, SafeArray<T> s) {
int size = s.high - s.low + 1;
for (int i = 0; i < size; i++) {
os << s.p[i] << endl;
}
return os;
}