I'm trying to learn C++ and figuring out how to access a private member variable that is an array of objects. My objective is trying to print out the data that's in the array of objects. Suppose that my header looks like this.
using namespace std;
const unsigned MAX_RESULTS = 10;
class StudentRecords{
public:
StudentRecords();
//bunch of other getters and setters here
Result GetResults() const; //my lame attempt at trying to access the obj-array private var
private:
Result results[MAX_RESULTS]; // array of Result of MAX_RESULTS number of elements
//+other private variables
};
ostream& operator <<( ostream& os, const StudentRecords& R);
In the above, there is supposed to be a private array of Result objects called results, which has a size of MAX_RESULTS, which is supposed to be 10 here. Now, using my overloaded operator << the idea is to print the contents of Result to 'file' so as to speak. Since it's an array, I want to print out all the results in the array using a for loop.
Result StudentRecords::GetResults() const
{
return results[MAX_RESULTS];
}
ostream & operator <<( ostream & os, const StudentRecords& R )
{
for(unsigned i = 0; i < SomeNumber; i++)
{
os << R.GetResults()[i] << '\n'; //this won't work of course see error
}
return os;
}
There will be an error stating:
error: no match for 'operator[]' (operand types are 'Result' and 'unsigned int')|
I already overloaded the << operator in my Result class in order to print out the values in that class. The problem is that I don't know how to iterate through the results array. From what I've googled I understand that you can use some kind of pointer function for example here: C++: Setters and Getters for Arrays
When I try to write the function like this:
Result* GetResults() const;
I will get an error stating:
error: cannot convert 'const Result' to 'Result*' in return|
Leaving out the * allows the code to compile, but predictably I get a bunch of garbage values from my array. So assuming that my class has an array of objects, and those objects have their own variables, how do I print out the values from my array of objects? I appreciate the help.