How to call original function after it's been overridden in C++?
I serialize most of my classes with two functions, read() and write(). What I would like to do is have the read/write() function of the base class called from the s开发者_运维百科ubclasses so that I don't have to repeat the serialization code multiple times.
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. Sub would then call Base::read(QDataStream&) and then add whatever attributes are unique to 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 (::).
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).
You can scope resolve and use the parent class version when you're in a subclass:
void Sub::read(QDataStream& qds) {
Base::read(qds);
// do more stuff
}
精彩评论