有时,我觉得方法超载可能会造成混乱。
class a {
public:
void copy(float f);
void copy(double d);
};
a me;
me.copy(1.2); // Not obvious at the first sight on which version we are calling.
解决方法是。
class a {
public:
void copyFloat(float f);
void copyDouble(double d);
};
然而,拥有不同名称的方法,执行相同的功能似乎也不是一个好主意。我可以知道,你有什么考虑,在方法重载或方法中选择不同的命名?
答案 0 :(得分:17)
肯定会超载。
好吧,所以并不是“显而易见”哪个函数被调用(可论证)......那又怎么样?你不关心它可以采取不同类型的参数,它只需要做它的事情。如果你根据不同的重载有不同的行为,你就滥用了重载,没有指出它们中的缺陷。
滥用重载的一个例子:
// good:
struct has_properties
{
void property1(float); // set property1, which happens to be a float
void property2(int); // set property2, which happens to be an int
};
// bad:
struct has_properties
{
void property(float); // set property1, abusing that it's a float
void property(int); // set property2, abusing that it's an int
};
希望你在这里看到问题。如果两个函数具有相同的名称,它们应该做同样的事情。
更好的是,如果您只是尝试允许在不同类型上操作,只需使用模板即可。 (这可能是一种超载的形式。)
答案 1 :(得分:2)
我会把它放在评论中,但我还不能。既然你把它标记为C ++,我想我应该告诉你,方法通常在C / C ++中被称为函数。
答案 2 :(得分:2)
尽量避免使用多个具有相同名称的虚拟方法。或者您可能希望在派生类中重写它们。请看以下示例:
#include <string>
struct Base {
virtual void foo(const std::string& arg) {
}
virtual void foo(int arg) {
}
};
struct Derived : Base {
// Only std::string version is overriden.
virtual void foo(const std::string& arg) {
}
};
int main() {
Derived d;
// This fails to compile because the name lookup stops
// after Derived::foo has been found.
d.foo(42);
}
答案 3 :(得分:1)
如果你基本上对这两个函数做同样的事情,它们只是在类型参数上有所不同,那么使用模板可能更有意义,而根本不使用重载。
答案 4 :(得分:0)
当然,在浮动与双重的情况下,你不应该超载,这太容易出错了。我听说有人争辩说你应该总是在这些情况下使用不同的名字,只是为了完全明确,让读者尽可能清楚,我倾向于同意。
答案 5 :(得分:0)
重载函数是用于对函数进行分组的C ++方法。
do_it (A a, B b);
do_it (B b, int i = 0);
具有不同名称的函数(例如do_it_with_a或do_it_with_a_b)是用于对函数进行分组的C方法。
因此,如果您的功能在行为上有所不同,请不要使它们超载。