这是一个关于想法而不是真实代码的问题
以前总是写很多方法重载,还好:
class myclass
{
public:
std::string method(type1 a)
{
return method(...);
}
std::string method(type2 a)
{
return ....;
}
}
那太棒了。
问题是从昨天写的函数重载is a namespace开始的:
namespac myspace
{
std::string func(type1 a)
{
return func(...);
}
std::string func(type2 a)
{
return ....;
}
}
这里的问题是在命名空间内部,编译器不知道第二个函数。因此,它会尝试将给定类型转换为与第一个函数匹配的类型。不幸的是,编译器没有告诉我这是我的错误。虽然我将 type2
发送给函数,但它试图将其转换为 type1
以调用自身,结果是一个 stackoverflow。
即使更改函数的顺序可以解决问题,我想知道在专业 C++ 编程中在命名空间中使用函数重载是不是一个坏主意?
最佳答案
正如有人评论的那样,这个问题不是函数重载的问题,而是函数声明顺序的问题。
当编译器看到时,您的命名空间中的错误很明显
std::string func(type1 a)
{
return func(/*expect type2*/);
}
此时它必须知道func(/*expect type2*/)
的原型(prototype)/定义。
但是,在您的类定义中:
class myclass
{
public:
std::string method(type1 a)
{
return method(/*expect type2*/); // OKAY, no problem here
}
std::string method(type2 a)
{
return ....;
}
}
尽管 method(/*expect type2*/)
的原型(prototype)/定义在该位置未知,但编译器不会抛出任何错误。为什么?
根据这个http://www.tutorialspoint.com/cplusplus/cpp_inline_functions.htm
A function definition in a class definition is an inline function definition, even without the use of the inline specifier.
也就是说,编译器在编译myClass
时,只编译成员prototype,当然,在这个例子中,没有错误。成员 definition 将在稍后编译,例如当您调用该成员时。此时,myClass
中所有成员函数的原型(prototype)都已经完全知道了。因此,编译器不会抛出任何错误。
编辑:命名空间是命名空间,类是类;他们有不同的含义。选择 namespace 还是类取决于您自己的情况,而不是希望摆脱函数顺序错误。在您的示例中,您仍然可以通过声明所有需要的原型(prototype)来使用命名空间:
namespac myspace
{
std::string func(type2 a); // prototype
std::string func(type1 a)
{
return func(...); // fine
}
}
因此,最佳实践始终是在定义/调用之前声明原型(prototype) :)
关于c++ - 命名空间中的函数重载(与具有静态成员的类相比)是个坏主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31395981/