官术网_书友最值得收藏!

Static keyword inside a function

The first one, being used inside of a function, basically means that once the variable has been initialized, it will stay in the computer's memory until the end of the program, keeping the value that it has through multiple runs of the function. A simple example would be something like this:

#include <string> 

class StaticExamples
{
public:
void InFunction()
{
static int enemyCount = 0;

// Increase the value of enemyCount
enemyCount += 10;

std::string toDisplay = "\n Value of enemyCount: " +
std::to_string(enemyCount);

printf(toDisplay.c_str());
}
};

Now if we were to call this, it would look something like the following:

  StaticExamples se; 

se.InFunction();
se.InFunction();

And when we call it, the following would be displayed:

As you can see, the value continues to exist, and we can access and/or modify its contents as we see fit in the function. This could be used for a number of things, such as maybe needing to know what happened the last time that you called this function, or to store any kind of data between any calls. It's also worth noting that static variables are shared by all instances of the class, and due to that, if we had two variables of type StaticExamples, they would both display the same enemyCount. We will utilize the fact that, if an object is created this way, it will always be available later on in this chapter.

主站蜘蛛池模板: 城口县| 方城县| 彭阳县| 天台县| 和林格尔县| 宁乡县| 永新县| 迁西县| 天全县| 海安县| 渝北区| 宜黄县| 孟村| 沐川县| 迁安市| 榆社县| 富源县| 长岭县| 黄冈市| 介休市| 九龙坡区| 板桥市| 永丰县| 新野县| 河南省| 乐都县| 淮南市| 黑龙江省| 北碚区| 渝北区| 凤台县| 江都市| 宿迁市| 兴安盟| 锡林浩特市| 綦江县| 潞西市| 新营市| 子洲县| 高陵县| 南部县|