[英]How to call original function after it's been overridden in C++?
I serialize most of my classes with two functions, read() and write().我用两个函数 read() 和 write() 序列化我的大部分类。 What I would like to do is have the read/write() function of the base class called from the subclasses so that I don't have to repeat the serialization code multiple times.
我想做的是从子类调用基本 class 的 read/write() function,这样我就不必多次重复序列化代码。
For example:例如:
class Base
{
public:
base();
virtual read(QDataStream&);
virtual write(QDataStream&);
private:
int a, b, c, d;
}
class Sub : public Base
{
public:
Sub();
read(QDataStream&);
write(QDataStream&);
private:
int e, f, g, h;
}
So in this example, i would like the code to read/write a,b,c,d to come from Base.所以在这个例子中,我希望读取/写入 a,b,c,d 的代码来自 Base。 Sub would then call Base::read(QDataStream&) and then add whatever attributes are unique to Sub.
然后,Sub 会调用 Base::read(QDataStream&),然后添加 Sub 独有的任何属性。 This way I don't have to repeat the serialization code for each subclass (and possibly forget to do so).
这样我就不必为每个子类重复序列化代码(并且可能忘记这样做)。
You can call base-class functions by prepending the function call with the base-class identifier, followed by the scope operator (::).您可以通过在 function 调用前加上基类标识符来调用基类函数,然后是 scope 运算符 (::)。
Like this:像这样:
class Base
{
public:
virtual void Function();
}
class Foo : public Base
{
public:
void Function();
void DoSomething();
}
void Foo::DoSomething()
{
Base::Function(); // Will call the base class' version of Function().
Function(); // Will call Foo's version of Function().
}
EDIT: Note removed by request.编辑:请注意删除。
void Sub::read(QDataStream &stream)
{
Base::read(stream);
// do Sub stuff here
}
First off - your member functions don't have return types - not valid in C++, your compiler might complain about 'default int' behavior and let it pass, but you should give them return types (I'll use void
as a placeholder).首先 - 您的成员函数没有返回类型 - 在 C++ 中无效,您的编译器可能会抱怨“默认 int”行为并让它通过,但您应该给它们返回类型(我将使用
void
作为占位符) .
You can scope resolve and use the parent class version when you're in a subclass:当您在子类中时,您可以 scope 解析并使用父 class 版本:
void Sub::read(QDataStream& qds) {
Base::read(qds);
// do more stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.