C++我在哪里需要本地扩展或外部方法?
我对 C++ 不太熟悉,不知道哪里需要这两个非常相似的重构(引入本地扩展和引入外部方法)。我知道强制使用这些的情况,但我无法计算出需要这种“技巧”的示例类。我正在制作 C++ 重构教程,以帮助新开发人员,但看起来我也需要您的帮助:)
如果您使用过它,请告诉我在哪里以及为什么。提前致谢。
I'm not familiar with C++ enough to know where those 2 very similar refactorings (introduce local extension and introduce foreign method) will be needed. I know cases that forces to use those, but I can't figure sample classes that will need this "trick". I'm making C++ refactoring tutorial, to help new developers, but it looks like I need yours help too :)
If you used it, please tell me in where and why. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“外部”方法是对类进行操作但不是类成员的方法。在 Java 中,这仅意味着其他类的(静态)方法将第一个类作为参数。在 C++ 中,您需要了解自由函数。与 Java 不同,C++ 中的方法可以存在于类之外。
int main()
是最著名的一个。 STL 还包含许多免费函数。就一个人进去看看吧。对于 Java,您链接的网站建议 “外部方法是一种解决方法” 和建议“引入本地扩展”作为替代重构。在 C++ 中,自由函数不是一种解决方法。这意味着引入本地扩展的压力要小得多。
此外,在 C++ 中,默认情况下函数不是虚拟的,并且对象通常按值传递。这意味着“引入本地扩展”技术常常会失败。
我希望这能够表明您的方法的根本问题:您正在采用 Java 重构技术,该技术解决了特定的 Java 弱点,并尝试将它们转换为具有一组相当不同的弱点的 C++。即使在有效的地方,它通常也是不必要的。
"Foreign" methods are methods that operate on, but aren't members of a class. In Java, that just means (static) methods of other classes that take the first class as an argument. In C++, you'll need to be aware of free functions. Unlike Java , in C++ methods can exist outside classes.
int main()
is the most famous one. The STL is also packed with free functions. Just have a peek in alone.For Java, the site you linked advises that "foreign methods are a work-around" and suggest "Introduce Local Extension" as a alternative refactoring. In C++, free functions are not a work-around. That means there's much less pressure to introduce local extensions.
Furthermore, in C++ functions are not virtual by default, and objects are often passed by value. This means that the "introduce local extensions" technique often fails.
I hope this goes to show the fundamental problem with your approach: you're taking refactoring techniques for Java, which address specific Java weaknesses, and try to convert them into C++ which has a rather different set of weaknesses. Even where it works, it's often unnecessary.