问题描述
我有一个C的背景。我只是想知道为什么函数重载加入到C ++? C没有函数重载,但是C ++呢,是什么需要吗?
I have a C background. I was just wondering why was function overloading added to C++? C doesn't have function overloading but C++ does, what was the need for it?
跨越语言设计者的头脑出了什么那个时候?
What went across the mind of the language designer at that time?
推荐答案
它提高了可维护性。如果你有一个类型T和你调用一个函数,那么你需要改变T,如果功能已重载新型T,那么你可以立刻重新编译。在C语言中,你将不得不回去挖通所有的呼叫地点和改变调用的函数。采取的sqrt()。如果你想SQRT()浮点型,那么你必须改变sqrtf()。
It increases maintainability. If you have a type T and you call a function with it, then you need to change T, if the function has been overloaded for the new T then you can recompile instantly. In C you would have to go back and dig through all the call sites and change the function called. Take sqrt(). If you want to sqrt() a float, then you have to change to sqrtf().
不仅如此,但C ++的类型系统的容量和复杂性远远超过C,并且必须有单独的函数名称为每个可能的过载会迅速耗尽的名字为实现同一目的的功能合理的游泳池,但采取不同的参数,因为现在有很多更多的参数取。
Not just that, but the volume and complexity of C++'s type system is far more than in C, and having to have separate function names for every possible overload would quickly exhaust the reasonable pool of names for functions that serve the same purpose but take different arguments, because now there's a lot more arguments to take.
例如,比较C和C ++字符串库。在C字符串库提供了一个方法来追加到一个字符串 - 的strcat()。 C ++的标准::字符串::追加有八个重载。那你想打电话给他们吗? append_a,append_b等?这就是ridiculous-它们都提供相同的功能,只是以不同的方式。
For example, compare the C and C++ string libraries. The C string library offers one method to append to a string - strcat(). C++'s std::string::append has eight overloads. What do you want to call them? append_a, append_b, etc? That's ridiculous- they all serve the same function, just in different ways.
编辑:是的真正值得一提的追加
是一个非常糟糕的例子,许多C ++字符串重载是非常多余。然而,这是更普遍的情况相比,而不是的所有这些重载的冗余。
It is actually worth mentioning that append
is a really bad example, many of the C++ string overloads are very redundant. However, this is more general case than that and not all of those overloads redundant.
这篇关于为什么函数重载加入到C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!