static and extern
static keyword makes global variables with limited scope. Scope of the file, the namespace, the class, and the function.
extern keyword allows access to global variables in other files.
// ExternTest.h
extern int globalValue;
void IncreaseValue();
// ExternTest.c
#include "ExternTest.h"
int globalValue = 2; // if this line contains static keyword, the main functions cause linker error.
void IncreaseValue()
{
globalValue++;
}
// Main.c
#include "ExternTest.h"
int main()
{
printf("%d", globalValue);
// ...
}
Static Variables in Functions (C-style)
void Accumulate(int number)
{
static int result = 0; // Initialization runs only once.
result += number;
std::cout << "result = " << result << std::endl;
}
int main()
{
Accumulate(10); // 10
Accumulate(20); // 30
return 0;
}
Static Member Variables
// Cat.h
class Cat
{
public:
Cat();
private:
static int mCount;
};
// Cat.cpp
int Cat::mCount = 0;
Cat::Cat()
{
mCount++;
}
// Main.cpp
Cat* myCat = new Cat(2, "Coco");
Cat* yourCat = new Cat(5, "Momo");
Cat* hisCat = new Cat(3, "Nana");
Cat* herCat = new Cat(4, "Pury");
// one mCount variable, its value is 4
There is only one copy per class for static member variables. So static member variables are included in the class memory layout, not in the object memory layout. There is only one instance of the variables so the necessary memory is held in the exe file.
Best Practice for Static Member Variables
1. Don't put static variables in functions. Put them in classes.
2. Use static member variables instead of global variables. (to limit scope)
3. There's no reason to use C-style static variables.
View Codes.
Static Member Functions
// Math.h
class Math
{
public:
static int Square(int number);
};
// Math. cpp
int Math::Square(int number)
{
return number * number;
}
Stiatic member functions are global functions, but they are limited by logical scope. These functions can only access static members of the class (can't access non-static members). You can call static functions without objects.
// Cat.h
class Cat
{
public:
Cat(const std::string& name);
static const char* GetName();
private:
char* mName;
static int mCount;
};
// Cat.cpp
int Cat::mCount = 0;
Cat::Cat(const std::string& name)
{
++mCount;
}
const char* Cat::GetName()
{
return mName; // Compile Error
}
'College Study > C++ (ENG)' 카테고리의 다른 글
[C++] Standard Template Library Container: Vector (ENG) (0) | 2022.01.02 |
---|---|
[C++] Exception (ENG) (0) | 2022.01.02 |
[C++] Inline Functions (ENG) (0) | 2022.01.02 |
[C++] Casting (ENG) (0) | 2022.01.02 |
[C++] Object-Oriented Programming: Interface (ENG) (0) | 2022.01.02 |
댓글