对于基类,我有一个参数的构造函数,该构造函数将std::istream& in
作为参数。假设in
是一个文件,其字段由逗号分隔:
c, Toyota , n, 157
r, Jaguar , u, 246, 0.2
c, Honda , b, 145
应该从每行中提取每个字段并放置在它们自己的变量中,除了以r
开头的行的最后一个字段,该字段应该留在std::istream& in
中以在派生类构造函数中使用。
我想知道是否有办法:
r
中保留以std::istream&
开头的行的最后一个字段的“值”怎么样
class Base {
std::string first;
char second;
int third;
public:
Base(std::istream& in) {
char dummy;
std::getline(in, first, ",");
in >> second >> dummy >> third;
}
};
class Derived : public Base {
double forth;
public:
Derived(std::istream& in) : Base(in) {
char dummy;
in >> dummy >> forth;
}
};
std::unique_ptr<Base> read(std::istream& in) {
std::string which;
std::getline(in, which, ",");
if (which == "c") {
return std::make_unique<Base>(in);
} else if (which == "r") {
return std::make_unique<Derived>(in);
}
}