I'm trying to pass a reference to an ofstream with an open file to an object, so that it's functions can also print to the file.
When I try to compile my program, it says that all reference members must be initialized, and I read online that streams cannot be reassigned. So what do I do?
Here's what I have for my constructors:
GameShow::GameShow(int numElements){
// Initialize heap
v = new Contestant[numElements+1];
capacity = numElements+1;
size = 0;
}
GameShow(int numElements, std::ofstream &of)
: outFile(of){
// Initialize heap
v = new Contestant[numElements+1];
capacity = numElements+1;
size = 0;
outputToFile = true;
handle.reserve(numElements+1);
handle.resize(numElements+1, -1);
}
And here is my declaration in my header file:
// Members
....
ofstream &outFile;
....
GameShow(int numElements);
GameShow(int numElements, std::ofstream &of);
....
I have the ofstream open in my main() function, but my object's functions need to be able to modify the same file... I feel like I've tried everything.
When I tried passing in the name of the file and trying to open it in append mode in the object and print to it, the output was all out of order and completely out of sync with the output from my main function. It seems as though all of the print statements I call from my object are being held in a buffer until my main function has closed the stream on its end. Any help would be greatly appreciated.
Attempting to use the constructor in my main function:
// Attempt to open output file
ofstream outFile;
outFile.open(outFileName);
if(inFile.is_open()){
if(outFile.is_open()){
// Get information
int numContestants = 0;
inFile >> numContestants;
// Process file
if(numContestants > 0){
GameShow gs(numContestants, outFile);
Errors (the only one im getting):
GameShow.cpp: In constructor ‘GameShow::GameShow(int)’:
GameShow.cpp:27:1: error: uninitialized reference member in ‘std::ofstream& {aka class std::basic_ofstream<char>&}’ [-fpermissive]
GameShow::GameShow(int numElements){
^
GameShow.h:14:18: note: ‘std::ofstream& GameShow::outFile’ should be initialized
std::ofstream &outFile;
^
make: *** [GameShow.o] Error 1
Reference members cannot be left uninitialized. You need to initialize outFile
in the GameShow(int numElements)
constructor as well.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments