不同的语言以不同的方式进行开发。特别是 C# 和 Java 对于 OO 有着强烈的观点,这导致一切都是对象心态(C# 在这里稍微宽松一些)。在这种方法中,扩展方法提供了一种扩展现有对象或接口以添加新功能的简单方法。
There are no extension methods in C++, nor are they needed. When developing C++, forget the everything is an object paradigm --which, by the way, is false even in Java/C# [*]. A different mindset is taken in C++, there are objects, and the objects have operations that are inherently part of the object, but there are also other operations that form part of the interface and need not be part of the class. A must read by Herb Sutter is What's In a Class?, where the author defends (and I agree) that you can easily extend any given class with simple free functions.
作为一个特别简单的例子,标准模板类basic_ostream
有一些成员方法来转储某些原始类型的内容,然后使用(也是模板化的)自由函数进行增强,这些函数通过使用现有的公共接口将该功能扩展到其他类型。例如,std::cout << 1;
被实现为成员函数,而std::cout << "Hi";
是在其他更基本的成员方面实现的自由功能。
C++ 中的可扩展性是通过自由函数实现的,而不是通过向现有对象添加新方法的方式实现的。
[*]一切都是not一个东西。
在给定的域中将包含一组可以建模的实际对象和可以应用于它们的操作,在某些情况下,这些操作将是对象的一部分,但在其他情况下它们不会。特别是你会发现实用程序类在声称一切都是对象的语言中实用程序类只是一个试图隐藏这些方法不属于任何特定对象这一事实的层。
即使某些作为成员函数实现的操作也不是真正对对象的操作。考虑添加一个Complex
数类,怎么样sum
(or +
)对第一个参数的操作比对第二个参数的操作更多?为什么a.sum(b);
or b.sum(a)
,不应该是sum( a, b )
?
强制操作成为成员方法实际上会产生奇怪的效果——但我们只是习惯了它们:a.equals(b);
and b.equals(a);
即使实施也可能会产生完全不同的结果equals
是完全对称的。 (考虑当以下任一情况时会发生什么a
or b
是一个空指针)