假设我有两个文件:
/**
* class.cpp
*/
#include <stdio.h>
class foo
{
private:
int func();
};
int foo::func(void)
{
printf("[%s:%d]: %s\n", __FILE__, __LINE__, __FUNCTION__);
return -1;
}
并且
/**
* main.cpp
*/
#include <stdio.h>
namespace foo
{
int func(void);
}
int main(void)
{
int ret = foo::func();
printf("[%s:%d]: ret=%d\n", __FILE__, __LINE__, ret);
return 0;
}
编译过程如下:
g++ -o a.out main.cpp class.cpp
有一个可执行文件的输出:
[class.cpp:15]: func
[main.cpp:14]: ret=-1
最后我的问题是:
为什么这个示例代码能够编译通过,我们可以调用类foo的私有方法?
使用gcc 4.6.3编译,但不仅限于此版本。 我知道编译器无法区分这两个符号(命名空间foo中的func函数和class foo中的私有函数foo)。nm的输出:
nm class.o
00000000 T _ZN3foo4funcEv
00000017 r _ZZN3foo4funcEvE12__FUNCTION__
U printf
nm main.o
U _ZN3foo4funcEv
00000000 T main
U printf
我想问这种行为是否正确?在我看来,这不是正确的行为,而且根本不安全(破坏了封装性)。
我想提一下,Visual Studio 2008的编译器不会链接这两个符号。
namespace foo { }
和class foo { }
,因此编译器没有真正需要以不同的方式装饰符号名称。 - Jonathan Potter