Problem using friend with the overload ostream operator

  • Thread starter Thread starter generalQuestions
  • Start date Start date
G

generalQuestions

Guest
My code consist of three files, the header file (ARRAY1.h), member function definition file (ARRAY2.cpp), and Main file (PRG8_2) which I've pasted here and separated each with "---------------------------". This code is not functional, its just used to figure out why when

friend ostream &operator<<(ostream &, const Array &) is called, it can't access the private member 'size' ------- given that it is known to be a friend of class Array. I'm not an experienced C++ programmer, any help would be appreciated. I'm using MS Visual C++ 2010 express edition.

The error I get is:

c:\users\workelf\documents\visual studio 2010\projects\fig8_2\fig8_2\array2.cpp(29): error C2248: 'Array::size' : cannot access private member declared in class 'Array'
1> c:\users\workelf\documents\visual studio 2010\projects\fig8_2\fig8_2\array1.h(19) : see declaration of 'Array::size'
1> c:\users\workelf\documents\visual studio 2010\projects\fig8_2\fig8_2\array1.h(9) : see declaration of 'Array'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========




//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Header file (ARRAY1.h)--------------------------------------------------------------
#ifndef ARRAY1_H
#define ARRAY1_H
#include <iostream>

class Array {
public:
Array(int = 10);

//friend functions
friend std::ostream &operator<<(std::ostream &, const Array &);

private:
int size;
};


//Array Class definitions (ARRAY2.cpp)---------------------------------------------------------
#include <iostream>
#include "ARRAY1.h"
using namespace std;

//Default constructor for class Array
Array::Array(int arraySize) {
size = arraySize;
}

//Overloaded ouput opertor for class Array
std::ostream &operator<<(std::ostream &output, Array &a) {
int i = 0;
if (i < a.size) //this is where error occurs
i = 1;

return output;
}


// Main (FIG8.cpp)-------------------------------------------------------------------------------------
#include <iostream>
#include "ARRAY1.h"
using namespace std;

int main() {
return 0;
}

Continue reading...
 
Back
Top