It runs fine when everything is in one file, but when I put the class, header, and driver in different files, I get errors. 11 errors to be exact. The first code is without modularization. The three after it is with modularization. I comment the error in the 3 after.
//IMPLEMENTATION
#include <iostream>
#include <string>
#include "Array.h"
usingnamespace std;
Array::Array()
{
}
Array::~Array()
{
}
int& Array::operator[] (string s) /* 5) 'int &Array::operator [](std::string)': overloaded member function not found in 'Array'*/
{
int index;
index = s[0] - 65; // or 13 instead of 65
while (ptr[index] != 0) /* 6) illegal reference to non-static member 'Array::ptr 7) 'Array::ptr': non-standard syntax; use '&' to create a pointer to member 8) subscript requires array or pointer type*/
{
index = (index + 1) % 6;
}
return ptr[index]; /* 9) illegal reference to non-static member 'Array::ptr' 10) 'Array::ptr': non-standard syntax; use '&' to create a pointer to member 11) subscript requires array or pointer type*/
}
int& Array::operator[] (int index)
{
return ptr[index];
}
Array::Array(int* p = nullptr, int s = 0)
{
size = s;
ptr = nullptr;
if (s != 0)
{
ptr = newint[s];
for (int i = 0; i < s; i++)
{
ptr[i] = p[i];
}
}
}
void Array::print()
{
for (int i = 0; i < size; i++)
{
cout << ptr[i] << " ";
}
cout << endl;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//DRIVER
#include <iostream>
#include <string>
#include "Array.h"
usingnamespace std;
int main()
{
int a[] = { 0, 0, 0, 0, 0, 0 };
Array arr1(a, 6);
arr1["Apple"] = 99; /* 3) binary '[': no operator found which takes a right-hand operand of type 'const char [6]' (or there is no acceptable conversion)*/
arr1[1] = 100;
arr1["Ape"] = 50; /* 4) binary '[': no operator found which takes a right-hand operand of type 'const char [4]' (or there is no acceptable conversion)*/
arr1.print();
return 0;
}
When you get multiple errors it's always best to start with the first error in the list because later errors can be side effects of the first error. Fixing the first error might fix many, if not all, of the other errors.
When I compile Array.h the first error I get is:
1 2 3
Array.h:15:19: error: declaration of ‘operator[]’ as non-function
int& operator[] (string s);
^~~~~~
This is a confusing error message to be honest, but the problem seems be that you have not put std:: in front of string.
int& operator[] (std::string s); // OK
After fixing this error the other files seem to compile just fine.