【发布时间】:2013-03-10 02:10:07
【问题描述】:
假设我有两个文件:
/**
* 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
最后是我的问题:
为什么这个示例代码编译没有任何错误,并且我们能够调用 class foo 的 private 方法?
使用 gcc 4.6.3 编译,但不仅如此。 我知道编译器不区分这两个符号(func 函数来自命名空间 foo 和私有函数 foo 来自 class 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 的编译器不会链接这两个符号。
【问题讨论】: