CyanMagentaYellowBlack CyanMagentaYellowBlack - 2 months ago 8
C++ Question

How do I access an array in my header file from my implementation file when overloading << operator?

If I take out the line where I am outputting the contents of data[], it compiles fine. I seem to be having trouble understanding accessing the array through the implementation file. Any help would be apprecciated.

implementation file function:

ostream& operator << (ostream& output, const Bag& b1)
{
for(int i = 0; i< b1.used; i++)
{
output <<Bag.data[i]<<" "; // LINE OF ERROR
}
output<<endl;
return output;
}


header file:

#ifndef BAG_H
#define BAG_H
#include <cstdlib>
#include <fstream>
namespace greg_bag{
using namespace std;


class Bag
{
public:
typedef int value_type;
typedef std:: size_t size_type;
static const size_type CAPACITY = 30;

Bag(){used = 0;}

void erase();
bool erase_one(const value_type& target);
void insert (const value_type& entry);
//void operator += (const bag& addend);

//size_type size()const {return used;}
//size_type count(const value_type& target) const;

//bag operator +(const bag& b1, const bag& b2);
friend ostream& operator << (ostream&, const Bag&);


private:

value_type data[CAPACITY];
size_type used;

};
}
#endif


error message:
error: expected primary-expression before '.' token|

Answer

data is not a static variable so that you can use it directly with class name. data is different for each instance of a class. Use the following code :

ostream& operator << (ostream& output, const Bag& b1)
{
   for(int i = 0; i< b1.used; i++)
   {
       output <<b1.data[i]<<" "; // LINE OF ERROR
   }
output<<endl;
return output;
}
Comments