The :: operator is used in two contexts.
Global Variable Resolution
The :: operator is used within C++ to identify global
variables that conflict with local variable names. Obviously it would be
good programming practice to use suitable names in the first place......
#include <iostream.h>
int Counter = 1;
main()
{
int Counter = 1;
for (int i=0; i< 10; i++)
{
cout << " Local Counter = " << Counter
<< " Global Counter = " << ::Counter
<< endl;
// Increment the local Counter.
Counter++;
}
exit(0);
}
|
#include <iostream.h>
// Define the Animal class
class Animal
{
public:
int GetNumOfLegs(void); // Declare a couple of methods
void SetNumOfLegs(int L);
private:
int Legs;
};
// Define the methods. The :: operator associates the method with
// the correct class.
int Animal::GetNumOfLegs(void)
{
return Legs;
}
void Animal::SetNumOfLegs(int L)
{
Legs = L;
}
//*******************************************************
main()
{
Animal Goat; // Create the goat object
Goat.SetNumOfLegs(4); // Initialise the Goat object with some legs
// Inform the user how many legs a goat has.
cout << "Goats have "
<< (int) Goat.GetNumOfLegs()
<< " legs"
<< endl;
exit(0);
}
|
Global
Variable Example Program.
C++ operators..
Global
Variables.
| Top | Master Index | Keywords | Functions |