我有一个简单的父类和基类:
class X
{
public:
virtual void Method(){...}
};
class Z : public X
{
public:
virtual void Method(){ X::Method(); }
};
我想重构这个新类Y
位于类层次结构的中间,所以 Z : Y
, Y : X
. Z::Method()
现在应该调用Y::Method()
不是 X::Method()
.但如果我不改变它,它仍然可以编译。事实上,我有很多这样的方法,很容易错过调用X::...
的电话。重构时会导致难以发现的错误。有没有办法让编译器提醒我,换句话说,使
X
Y
可以访问的方法, 但对 Z
隐藏?澄清一下,这可能只是我进行重构以确保不会遗漏任何内容时的临时更改。
最佳答案
But if I don't change this, it still compiles. In truth I have a lot of such methods and it's very easy to miss a call to X::... when refactoring which would lead to hard to find bugs.
To clarify, this may only be a temporary change while I am doing the refactoring to make sure I don't miss anything.
正如您所描述的“重构时”,您可以临时添加一个不完整的类型
X
至Z
遮蔽了父类(super class)X
向上层级:class Z : public Y {
private:
struct X; // TODO(Mr. Boy): remove after finishing re-factoring.
public:
void Method() override { X::Method(); } // error! Z::X is incomplete
};
对 X::...
的任何合格使用在 Z
将失败,因为查找解析为不完整的嵌套类型 X
.
关于c++ - 防止孙子调用其祖 parent 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65956771/