在子类中调用父函数
Call parent function inside of child class
class Parent;
class Child;
Parent *parent;
ifstream inf("file.csv");
inf >> *parent;
//in parent class
friend istream& operator>> (istream &is, Parent &parent) {
return parent.read(is);
}
virtual istream& read(istream &is){
char temp[80];
is >> temp;
// then break temp into strings and assign them to values
return is;
}
//virtual istream& read
它仅读取前两个值并将其分配给父类。 Child
类有自己的Parent
类值 + 3。
如何调用我调用父级的read()
函数,然后调用子级的read()
函数,以便父级函数读取文件中的前 2 个字段,子函数读取接下来的 3 个字段?
我知道这是语法问题;我只是不知道该怎么做。我试过在孩子阅读课内打电话给Parent::read(is)
,我试过在孩子read()
之前打电话;我试过read(is) >> temp
但没有一个奏效。当我调用Parent::read(is)
然后is >> temp
时,父is
将返回文件的所有 5 个值。
在这种情况下,
您通常会让 Child 覆盖 Parent 中的 read
函数。这允许派生类在应用其自己的逻辑之前调用父类中的原始函数。
class Parent
{
public:
virtual void read(istream &s)
{
s >> value1;
s >> value2;
}
};
class Child : public Parent
{
public:
virtual void read(istream &s)
{
Parent::read(s); // Read the values for the parent
// Read in the 3 values for Child
s >> value3;
s >> value4;
s >> value5;
}
};
执行读取操作"
// Instantiate an instance of the derived class
Parent *parent(new Child);
// Call the read function. This will call Child::read() which in turn will
// call Parent::read()
parent->read(instream);
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销