关于名字演绎(可能题目描述不太准确)最近遇到的一个问题,希望有人能解答。情况一(没有写完整代码):int c;cl
关于名字演绎(可能题目描述不太准确)
最近遇到的一个问题,希望有人能解答。
情况一(没有写完整代码):
int c;
class c{};
cout<<sizeof(c);
这个时候输出为4,如果用cout<<sizeof(class c);则输出1。
情况二:
namespace temp{
int c;
}
class c{};
cout<<sizeof(c);
这个时候编译器提示c有二义性,在c前加上关键词限定后即可通过编译。
现在的问题是,sizeof中的参数c是通过怎样一种机制去确定c到底是指哪一个?
情况一中的两个c定义顺序不会影响结果,这个已经试过了。 实参演绎
[解决办法]一,c++11 3.3.10/2
A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member, function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.
因此 sizeof(c) 看到的 c 是 int c;
二,unqualified name lookup 只能找到 class c; 因为 temp::c 不可见,所以不存在二义性。你的编译器认定二义性是编译器的 bug。
[解决办法]楼主应该是少写了一句:
using namespace temp;
如果哪个编译器出现这种bug,那它应该已经死掉了。
[解决办法]我也猜的是这个原因,不过还是选择严格按照主楼的程序解释。因为我觉得做技术要严谨,所以假设楼主没把那关键的一句漏发上来。