我有一堂课,如下所述:
class InputReader
{
public:
typedef void (*handler)(std::string, int);
static void errorHandler(std::string error, int severity); //Supplies a default error handler
static void warningHandler(std::string error, int severity); //Supplies a default warning handler
handler errorH;
handler warningH;
InputReader(std::string pwd = "", handler eHandler = errorHandler, handler wHandler = warningHandler);
bool readFile(std::string filename);
std::vector<first> mesh;
//other irrelevant objects that need to be read into
};
first
是一个结构:
struct first
{
std::string filename;
double scale;
};
在Mooing Duck的帮助下,我有:
std::istream& operator>>(std::istream& file, first& obj)
{
std::string symbol;
while(file >> symbol)
{
if (symbol[0] == '#')
{
std::getline(file, symbol);
}
else if (symbol == FIRSTTAGEND)
{
break;
}
else if (symbol == FILEPATH)
{
if (!(file >> '=' >> obj.filename))
std::cerr << symbol << " is incorrectly formatted"; //This needs to use errorH
}
else if (symbol == SCALE)
{
if (! (file >> '=' >> obj.scale) )
std::cerr << symbol << " is incorrectly formatted"; //This needs to use errorH
}
else
{ //not a member: failure
std::cerr << symbol << " is not a member of first";
file.setstate(file.rdstate() | std::ios::badbit);
break;
}
}
return file;
}
std::istream& operator>>(std::istream& file, InputReader& obj)
{
std::string symbol;
while(file >> symbol)
{
if (symbol[0] == '#')
{
std::getline(file, symbol);
}
else if (symbol == FIRSTTAGBEG)
{
first t;
if (file >> t)
obj.mesh.push_back(t);
}
else
{
obj.errorH(symbol + " is not a member of the input reader.", 1);
file.setstate(file.rdstate() | std::ios::badbit);
}
}
return file;
}
bool InputReader::readFile(std::string filename)
{
std::ifstream infile;
infile.open(filename.c_str());
infile >> *this;
return true;
}
errorH
在构造 InputReader 对象时设置。它可以由该类的用户提供,否则,它使用我提供的默认值。errorH
唯一的问题是当first
被读入时我无法访问。我该如何解决这个问题?
问题限制:不允许使用外部库。不允许使用 C++11/C++OX。