|
|
|||
![]() |
Department of Engineering |
| University of Cambridge > Engineering Department > computing help > Languages > C++ |
The static keyword is used in 3 contexts for 3 reasons.
| file1.cc | file2.cc | g++ file1.cc file2.cc |
| int main() { int i=cloud; } | int cloud=9; | file1.cc:2: error: cloud was not declared in this scope |
| extern int cloud; int main() { int i=cloud; } | int cloud=9; | (compiles ok) |
| extern int cloud; int main() { int i=cloud; } | const int cloud=9; | link error: undefined reference to `cloud' |
| extern int cloud; int main() { int i=cloud; } | extern const int cloud=9; | (compiles ok) |
int counter() {
static int count=0;
count++;
cout << count << endl;
}
class little {
int i;
};
"little l1, l2;" would create 2 objects of that class, each with
their own i variable. In contrast,
class little {
static int i;
};
little l1, l2;
creates 2 objects but only 1 variable called i - the i
belongs to the class rather than to individual objects. This is useful if,
for example, you want to keep a count of how many objects of a particular
class have been created. In some situations it also saves memory. Class
functions can also be static.
| | 1A C++ Frequently Asked Questions | C++ | Languages | computing help | |