我可以使用父read()
函数读取名字和姓氏,然后让孩子read()
读取中间名吗?或者我必须在孩子身上阅读第一,第二和中间?
编辑:第一个答案似乎有效,但是当我在 child using 中阅读时strtok
,我得到了整行,而不仅仅是第三个字段。有没有办法解决它,或者我只需要将前两个字段读入虚拟变量,然后再读取第三个字段?
class Parent
{
protected:
char first[80], last[80];
virtual istream& read(istream &is) {
char temp[80];
char *f, *l;
is >> temp;
f = strtok(temp, ",");
strcpy(first, f);
l = strtok(NULL, ",");
strcpy(last, l);
return is;
}
public:
friend istream& operator>> (istream &is, Parent &parent) {
return parent.read(is);
}
};
class Child: public Parent
{
char middle[80];
istream& read(istream &is) {
/*inherit first and last from parent*/
char temp[80];
char *m;
is >> temp;
m = strtok(temp, ",");
strcpy(middle, m);
}
};
in main()
Parent *object;
ifstream inf("filename.csv");
object = new Child();
inf >> *object;
猫文件名.csv
George,Bush,Walker