My "Record" Constructor looks like this:
#include "Record.h" //both these headers #include <iostream>
#include "String.h"
Record :: Record(std::ifstream& is)
{
std :: istream & iss = static_cast<std::istream &>(is);
iss >> ID >> medium >> rating;
getline(iss, title);
if (!iss.good())
throw Record_exception(invalid_data);
}
where ID is an int, medium and title are a user-defined type String (not the standard string) for which operator>> , getline, and operator<< are defined on an istream as follows
#include "String.h"
ostream& operator << (ostream& os, const String & s)
{
int str_length = s.size();
for (int i = 0; i < str_length ; i++)
os << s[i];
return os;
}
istream& operator >> (istream& is, String& str)
{
char input;
bool string_end = false;
int length = 0;
str.clear();
while (!string_end){
is.get(input);
if (!isspace(input) && is){
length++;
str +=input;
}else if (length || !is)
string_end = true;
}
return is;
}
istream& getline(std::istream& is, String& str)
{
char input;
bool string_end = false;
int length = 0;
str.clear();
while (!string_end){
is.get(input);
if (!isspace(input) && is){
length++;
str +=input;
}else if ((length && is.peek() == '\0') || !is)
string_end = true;
}
return is;
}
i static_casted the ifstream to an istream because i realized the compiler wasn't accepting my "getline" and operator<< for String and operator<< for string with an ifstream. I still do not know if this is the correct approach however
my compiler error NOW includes:
"Record.cpp: In constructor ‘Record::Record(std::ifstream&)’: Record.cpp:26: error: invalid static_cast from type ‘std::basic_ifstream >’ to type ‘std::istream&’
i am compiling with flags "g++ -c -pedantic -Wall -fno-elide-constructors" on a red_hat linux machine
In your case, I think you have to understand that ifstreams implement the istream interface. Your Record constructor actually does not need an ifstream. All the code inside makes use only of istream's public interface. So you only need to make your Record constructor take istream& (not ifstream&). This will also make your Record class more general since you can use it with all kinds of istreams, not just file input streams.
However, your String class overloads look fine. I suspect from the way you're trying to static_cast fstream to istream (this is an upcast and should never be required explicitly and also shouldn't be done), the original problem you were trying to work around is that you don't have the proper headers included in all relevant areas. Make sure you have istream, ostream, and fstream included where necessary, and not simply iosfwd or iostream. If the compiler is giving you errors trying to pass an fstream reference to a function that expects istream&, something is definitely wrong and the most likely explanation is forward declarations and missing includes.