确定派生类是否重写基类的方法
class B {
virtual int foo();
};
class D : public B {
virtual int foo() { cout<<"D\n"; }
};
int B::foo()
{
/* how do i tell if this->foo() is overridden by a subclass, or if it will */
/* simply recurse into B::foo()? */
this->foo();
}
main()
{
D d;
d.B::foo();
}
class B {
virtual int foo();
};
class D : public B {
virtual int foo() { cout<<"D\n"; }
};
int B::foo()
{
/* how do i tell if this->foo() is overridden by a subclass, or if it will */
/* simply recurse into B::foo()? */
this->foo();
}
main()
{
D d;
d.B::foo();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
答案:你不能。
如果有什么可以扩展的,我会扩展。
Answer: you can't.
I'd expand if there was anything to expand upon.
一种方法是在
B
中使foo()
纯虚函数,和也定义它。这样您就可以确保B
的派生类必须定义foo()
。这是 B,如果 B 的派生类没有实现 foo(),那么你甚至无法创建此类派生类的实例!
请参阅 ideone 上的完整工作代码: http://www.ideone.com/m8O2s
顺便说一下,我个人的观点是,这样的类设计一开始就不好。如果从派生类 foo() 调用
B::foo()
会怎样?递归?One approach is to make
foo()
pure virtual function inB
, and also define it. That way you make sure that the derived classes ofB
must definefoo()
. Here is B,If a derived class of B doesn't implement foo(), then you cannot even create instance of such derived class!
See the complete working code at ideone : http://www.ideone.com/m8O2s
By the way, my personal opinion would be, such design of classes is bad to begin with. What if you call
B::foo()
from the derive class foo()? Recursive?我什至讨厌提供这个..但这里是
编辑
我想证明它在MSVC++ 2010中有效。
输出
证明它并不总是有效
把D改成这个就不行了
I hate even providing this.. but here it is
Edit
I want to prove that it works in MSVC++ 2010.
Output
Proof it won't always work
Change D to this and it won't work anymore
正如其他人指出的那样,没有可靠的方法可以做到这一点。我敦促你重新考虑你的设计......
As others have pointed out, there is no reliable way to do this. I urge you to rethink your design...
最安全的方法是根本不重写 foo(),但如果您不信任程序员,则允许重写从基类调用的 OnFoo() 函数。 MFC 做了很多这样的事情来确保某些默认行为(而不是防止递归)。
然后,同样在静态级别,任何实现 OnFoo() 的内容都可以通过“在文件中查找”轻松发现。
例如(未测试语法/编译且不是线程安全的)
The safest way is by not overriding foo() at all, but allow overriding of an OnFoo() function which is called from the baseclass if you cannot trust your programmers. MFC does a lot of this to ensure some default behaviour (rather than protect against recurision).
Then, also at a static level, anything that implements OnFoo() is easily spotted with a 'Find in files'.
E.g. (not tested for syntax/compilation and not threadsafe)