Wayne Shu wrote:
see the following code from the book C++ Templates The Complete Guide
#include <iostream>
int C; // (1)
class C // (2)
{
private:
int i[2];
public:
static int f(){
return sizeof(C);
};
};
int f()
{
return sizeof(C);
}
int main()
{
std::cout << "C::f() " << C::f() << ","
<< "::f() " << ::f() << std::endl;
return 0;
}
why the result of the program is
C::f() 8,::f() 4
why the two names C are not ambiguous.
Where? In the 'main', when you write 'C::' you cannot mean the 'int'
variable, can you? The name preceding the scope resolution operator
is always looked up among classes and namespaces.
In the 'C::f' member, 'C' _hides_ the 'int' variable declared outside
of the class itself. So, 'sizeof(C)' in 'C::f' has no ambiguity.
if aren't ambiguous ,why the name C(2) doesn't hide the name C(1).
It does. But only in the nested scope -- in the class itself.
why in function f(), the C refer to the C(1).
Because outside the scope of the class C, the _class_ C has to be
referred to with 'class C' syntax (specifically for disambiguation
purposes). Or, in a particular context ("blah::") only names of
classes and namespaces are looked at.
The co-existence of variable 'C' and 'class C' is allowed for
compatibility with the C language, where you are allowed to have
both 'X' object and 'struct X', and no ambiguity exists because
the latter always has to be supplied the 'struct' keyword.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask