我有这个结构:
class A
{
public:
virtual void func(int a)
{
cout << "System is initiated correctly." << a;
}
};
class B : public A
{
public:
virtual void func(int a) override
{
A::func(a);
cout << "This particular system is initiated correctly too" << a;
}
};
现在95%的情况下,当我从A升级时,我覆盖func
,在100%的情况下我应该在做其他事情之前调用A::func();
?如何防止手动编写。有时我甚至忘记在子类中调用A::func();
并获得运行时错误,抛出等等。
答案 0 :(得分:16)
NVI pattern怎么样?
class A
{
public:
void func(int a)
{
cout << "System is initiated correctly." << a;
do_func(a);
}
private:
virtual void do_func(int a) {}
};
class B : public A
{
private:
virtual void do_func(int a) override
{
cout << "This particular system is initiated correctly too" << a;
}
};