The Scope Resolution Operator. McGraw-Hill The Complete Reference Fourth Edition
Hirdetés
Hirdetés
C h a p t e r 1 2 : C l a s s e s a n d O b j e c t s
319
The Scope Resolution Operator
As you know, the :: operator links a class name with a member name in order to tell the compiler what class the member belongs to. However, the scope resolution operator has another related use: it can allow access to a name in an enclosing scope that is "hidden" by a local declaration of the same name. For example, consider this fragment: int i; // global i void f()
{ int i; // local i
}
.
.
i = 10; // uses local i
.
As the comment suggests, the assignment i = 10 refers to the local i. But what if function f( ) needs to access the global version of i? It may do so by preceding the
i
with the :: operator, as shown here.
int i; // global i void f()
{ int i; // local i
}
.
.
::i = 10; // now refers to global i
.
Nested Classes
It is possible to define one class within another. Doing so creates a nested class. Since a class declaration does, in fact, define a scope, a nested class is valid only within the scope of the enclosing class. Frankly, nested classes are seldom used. Because of
C++'s flexible and powerful inheritance mechanism, the need for nested classes is virtually nonexistent.
Letöltés
Hirdetés