void foo()
{
bar(); // error: ‘bar’ has not been declared
}
void bar()
{
}
namespace N
{
void foo()
{
N::bar(); // error: ‘bar’ is not a member of ‘N’
}
void bar()
{
}
}
class C
{
static void foo()
{
C::bar(); // works just fine
}
static void bar()
{
}
};
处理函数调用高于其声明的这种不一致背后的理由是什么?为什么我可以在类中完成,而不能在命名空间或全局范围内完成呢?
发布于 2012-08-06 10:59:41
可以在类内部定义成员函数,也可以在类声明之后定义成员函数,也可以在每个类声明之后定义成员函数。
为了在这里获得一些一致性,具有内联定义的函数的类的规则是,它仍然必须编译,就好像函数是在类之后定义的一样。
你的代码
class C {
static void foo()
{
C::bar(); // works just fine
}
static void bar()
{ }
};
编译与
class C {
static void foo();
static void bar();
};
void C::foo()
{ C::bar(); }
void C::bar()
{ }
现在可见性不再有魔力,因为所有函数都可以看到类中声明的所有内容。
发布于 2012-08-06 10:13:27
你可以写
namespace n
{
void foo();
void bar()
{
foo();
}
void foo()
{
}
}
但不是
class C
{
void foo();
void bar()
{
foo();
}
void foo()
{
}
}
因此,类更需要这样的功能,并且为它们实现它比为命名空间实现它容易得多。
发布于 2012-08-06 09:52:27
嗯,也许是因为你把类声明放在一个地方,编译器可以很容易地获得它的成员信息。
另一方面,名称空间可以包含大量不同的文件,您不能期望编译器查看这些文件,因为它不知道首先在哪里查找。
要避免这种情况,只需使用function prototypes即可。
https://stackoverflow.com/questions/11825902
复制