I'm trying to overload ofstream and ostream operators but I have a problem. I'm saving active game while using ofstream and printing on terminal by using ostream.
Here's the error I get:
hex_game.cpp: In member function ‘void Hex::saveGame(const string&)’:
hex_game.cpp:375:18: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
375 | myfile << (*this);
| ^
hex_game.cpp:193:11: note: candidate 1: ‘std::ofstream& operator<<(std::ofstream&, const Hex&)’
193 | ofstream& operator <<(ofstream& fileOutput, const Hex& obj){
| ^~~~~~~~
hex_game.cpp:207:10: note: candidate 2: ‘std::ostream& operator<<(std::ostream&, Hex&)’
207 | ostream& operator <<(ostream& outputStream, Hex& obj){
LINE 375:
void Hex::saveGame(const string& file_path){
ofstream myfile;
myfile.open(file_path);
myfile << (*this);
cout << "Game has been saved!" << endl;
myfile.close();
}
Definition of ostream [FOR PRINTING THE BOARD ON TERMINAL]
ostream& operator <<(ostream& outputStream, const Hex& obj){
if(obj.getGameplayType() == 1){
outputStream << "Player1's Score: " << obj.getScoreP1() << " points" << " | Player2's Score: " << obj.getScoreP2() << " points";
}
else{
outputStream << "Player's Score: " << obj.getScoreP1() << " points";
}
outputStream << "\n\n ";
for(int i=0; i<obj.getBoardSize(); i++){
outputStream << " " <<obj.hexCells[0][i].column;
}
outputStream << endl;
for(int i=0; i<obj.getBoardSize(); i++){
outputStream << i + 1;
if(i+1 < 10) outputStream << " ";
if(i >= 1){
for(int j=0; j<i; j++) outputStream << " ";
}
for(int k=0; k<obj.getBoardSize(); k++){
outputStream << " " << obj.hexCells[i][k].point;
}
outputStream << endl;
}
return outputStream;
}
Definition of ofstream [FOR SAVING THE ACTIVE GAME INTO A .TXT FILE]
ofstream& operator <<(ofstream& fileOutput, const Hex& obj){
fileOutput << obj.getGameplayType() << endl;
fileOutput << obj.getBoardSize() << endl;
fileOutput << obj.getTurn() << endl;
for(int i=0; i<obj.getBoardSize(); i++){
for(int k=0; k<obj.getBoardSize(); k++){
fileOutput << obj.hexCells[i][k].point;
}
fileOutput << endl;
}
return fileOutput;
}
I searched my answer on net and I get some help but I did not fix this error yet. I fixed other ambiguity problem by adding explicit keyword before Hex constructors but this one is not fixed. Can someone help me?
(I must overload << for both ostream and ofstream. This is my homework and my teacher wants like that)
Aucun commentaire:
Enregistrer un commentaire