Reputation: 977
I have an 'IntList' class with a dynamic array of integers, but the following fragment of test code gives me troubles:
main.cpp
#include <iostream>
#include "IntList.hpp"
using std::cout;
using std::endl;
int main(int argc, const char * argv[]) {
IntList list{};
cout << "list-1 -> " << list << endl;
return 0;
}
IntList.hpp:
#ifndef IntList_hpp
#define IntList_hpp
#include <stdio.h>
using std::ostream;
class IntList
{
public:
int *dynarray;
int capacity;
int used;
IntList();
void pushBack(int x);
int getCapacity();
void print(ostream& sout);
};
#endif
IntList.cpp
#include <iostream>
#include "IntList.hpp"
using std::cout;
using std::endl;
using std::string;
using std::ostream;
IntList::IntList()
{
int capacity = 1;
int used = 0;
int *dynarray = new int[capacity];
}
ostream& operator<<(ostream& sout, const IntList& list)
{
for (int i = 0; i < list.used; ++i)
sout << list.dynarray[i] << " ";
return sout;
}
From what I understood, I tried to overload the << operator with this: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'ostream') but I don't know where I get it wrong because XCode gives me this error:
Invalid operands to binary expression ('basic_ostream<char>' and 'IntList')
Any idea how to solve this ?
Upvotes: 1
Views: 2743
Reputation: 51825
It appears (from the fragments you have shown) that there is no declaration of your <<
override in the header file (IntList.hpp
). Thus, the code in your main
function is not (and cannot be) aware of that override, which is provided in a separate source file.
You need to add a declaration of that override function in the header (tyically, just after the class definition), like this:
// Declaration (prototype) of the function for which the DEFINITION is provided elsewhere
extern ostream& operator<<(ostream& sout, const IntList& list);
Further, your IntList
constructor has some serious faults. In it, you are assigning values to three local variables (whose data will be completely lost when the constructor finishes). Those variables are hiding the member variables with the same names. Use this, instead (i.e. remove the int
declaration specifiers):
IntList::IntList()
{
// int capacity = 1; // This declares a local variable that hides the member!
capacity = 1;
used = 0;
dynarray = new int[capacity];
}
Upvotes: 4