C + + Those details--static keyword __c++

Source: Internet
Author: User
Tags class definition

Static is also the keyword we use frequently, and there are many uses for static, and static has different meanings in process-oriented and object-oriented programming. Before always remember, so, I obsessive-compulsive disorder again attack, must understand it ...


the static keyword in process programming 1. Static global variable static global variable:

C++test.cpp: Defines the entry point for a console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

static int s_test;
int nons_test;

int _tmain (int argc, _tchar* argv[])
{
	
	//static global variable default initialized to 0
	cout<< "static:" <<s_test<< Endl;
	Non-static global variable default initialization is also 0, but if it is a local non-static variable, the direct error in VS, can not be compiled
	cout<< "non-static:" <<nons_test<<endl;

	System ("pause");
	return 0;
}

Result: static:0
non-static:0
Please press any key to continue ...

When we run the program, memory is divided into code area, global data area, heap area, stack area. Normal temporary variable auto, etc. are in the stack area, the life cycle is the end of the function, and new objects are generally in the heap area, the declaration cycle is controlled by us, new start, delete when the end. The global data area saves global variables and static variables, and their lifecycle is the lifecycle of the entire program.
Difference between using a static global variable and using a normal global variable: 1 if the global variable is in the header file, or if the use and definition are in the same file, the static global variable is the same as the normal global variable.
The StaticTest.h header file defines static global variables and ordinary global variable static
int static_num =;
int nonstatic_num = 30;

C++test.cpp: Defines the entry point for a console application.
//global variable in header file or this file is not the difference between the two

#include "stdafx.h"
#include <iostream>
#include <string>
#include "StaticTest.h"
#include "StaticTest1.h"
using namespace std;


int _tmain (int argc, _tchar* argv[])
{
	
	//If the static variable is in the header file or in this file, you can access the static global variable
	cout<< "static:" << static_num<<endl;
	If the static variable is in the header file or in this file, you can access the non-static global variable
	cout<< "non-static:" <<nonstatic_num<<endl;

	System ("pause");
	return 0;
}

Result: static:20
Non-static:30
Please press any key to continue ...


2 If the global variable is in the. cpp file, the normal global variable is globally visible, and other files are visible, but when you use it, you add the extern keyword to the other files. And if you do not add, in this file and then declare a variable of the same name, it will be an error. However, static global variables can be used to solve this problem, static global variables in other files are not visible, we do not need to focus on other files of global variables, there will be no use of the same name global variables.
. H file
#ifndef __statictest1_h_
#define __statictest1_h_
#pragma once
class StaticTest1
{
Public:
	StaticTest1 (void);
	Virtual ~statictest1 (void);
#endif

//.cpp file
#include "stdafx.h"
#include "StaticTest1.h"

//define global variable static int in the. cpp file
Static_test = ten;
int nonstatic_test =;

Statictest1::statictest1 (void)
{
}


statictest1::~statictest1 (void)
{}
Main function File:
C++test.cpp: Defines the entry point for a console application.
//

#include "stdafx.h"
#include <iostream>
#include "StaticTest1.h"
using namespace std;

extern int nonstatic_test;
extern int static_test;

int _tmain (int argc, _tchar* argv[])
{
	
	//If static variables cannot be accessed in other. cpp files, static global variables are not accessible even if you use extern declarations in this file
	//cout< < "static:" <<static_test<<endl;
	If the static variable is in a different. cpp file, you can access a non-static global variable, but use the extern declaration in this file
	cout<< "non-static:" <<nonstatic_test<< Endl;

	System ("pause");
	return 0;
}

When extern is not added, the static global variable is undefined, and even adding an extern declaration is an error: C++test2.obj:error LNK2001: unresolved external symbol "int static_test" (? static_test@@3ha)
1&GT: Fatal error lnk1120:1 an unresolved external command


With regard to static global variables, there are three points to note: 1 static global variables, if uninitialized, are initialized to 0 instead of static global variables, note that global variables, and the initial value is 0. (Non-static non-global variables without initializing a direct error in VS) 2) Static global variables are not matched in the global data area, so the lifetime of the variable is the entire program's running period. (The lifetime of a local static variable is also the entire program run period) 3) the static global variable is visible in the file of the variable declaration, but it is not seen in other files.
About Global variables: if we put the global variable directly in the header file, the variable will be introduced into each file with the introduction of the header file. Sometimes this is something we don't want to see, so the other way is to put the global variables in the. cpp file so that global variables are not introduced everywhere with the. h file, and are not globally visible. However, this variable is still a global variable, and in order to use the variable in another file, declare it using the extern keyword in this file. If you do not, you will receive a case where the variable is not declared. If you define a variable with the same name directly in this variable, there will be a flush definition, which is what we don't want to see, if the global variable is only useful in this file, then use the static global variable directly.

2. Static local VariablesLocal variables, that is, variables stored in the stack space, when we call the function, the variable is initialized, and when the function call ends, the lifetime of the local variable ends and is destroyed. And sometimes we need to save the variables between the two call functions, the simplest idea is to use a global variable, but this variable is already not part of the function itself, but the global visibility, does not conform to the local principle, to the maintenance of inconvenience. Static local variables can just solve the problem. Static local variables are stored in the global data area and are not destroyed by the end of the function, and in other functions, static local variables are not visible and just meet our needs.
Let's look at an example:

C++test.cpp: Defines the entry point for a console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector >
using namespace std;


void TestFunc ()
{
	//defines a static local variable, but the variable is initialized only the first time, and the
	static int static_num = Ten is not initialized again when called again;
	But ordinary local variables, each of which will initialize
	int nonstatic_num =;
	static_num++;
	nonstatic_num++;
	cout<< "non_static:" <<nonstatic_num<< "  static:" <<static_num<<endl;
}

int _tmain (int argc, _tchar* argv[])
{
	//call 10 times for
	(int i = 0; i < i++)
		TestFunc ();

	System ("pause");
	return 0;
}

Results:

Non_static:11 static:11
Non_static:11 Static:12
Non_static:11 static:13
Non_static:11 static:14
Non_static:11 static:15
Non_static:11 static:16
Non_static:11 static:17
Non_static:11 static:18
Non_static:11 static:19
Non_static:11 static:20
Please press any key to continue ...


From the results above we can see that the function was called 10 times, the non-static variable is initialized each time, so the result is unchanged. Static variables are initialized only once, so each result is 1 larger than the previous one.


Some points to note about local static variables:

1 Local static variables also allocate memory in the global data area and are not destroyed because the function call ends.

2 The local static variable is initialized when it is first invoked to the variable and is not initialized again after it is called again. and local static variables are typically initialized at the declaration, and if uninitialized is not displayed, the default is initialized to 0

3 The life cycle of the local static variable is declared to the end of the program, but its scope is local, only in this function, does not break the principle of local.


3. Static function functions are globally visible by default, and if we want a function to be visible only in this file, you can declare it as a static function. This is about the same as static global variables. An example:

StaticTest.h
#include <iostream>
using namespace std;


void Normalfunctest ();

static void Staticfunctest ();

StaticTest.cpp
#include "stdafx.h"
#include "StaticTest.h"


void Normalfunctest ()
{
	cout< < "Normal func!" <<endl;	
}

static void Staticfunctest ()
{
	cout<< "static func!" <<endl;
}

C++test.cpp: Defines the entry point for a console application. The
//main function

#include "stdafx.h"
#include <iostream>
#include "StaticTest.h"
using namespace Std;


int _tmain (int argc, _tchar* argv[])
{
	normalfunctest ();
	Staticfunctest ();

	System ("pause");
	return 0;
}
In this example, there are two functions that are defined in another file, one as a normal function and the other as a static function. If you compile, you will receive the following error:
\vs2012\vs12\vc\include\xlocnum (): Error C2129: static function "void staticfunctest (void)" declared but undefined

That is, the compiler sees only the declarations in the. h file, but does not see the implementation in the. cpp file. In this way, the purpose of static is achieved. However, if the implementation of the function is placed in. h, then, whether it is static or not, it can be used.

two. Static keyword in object-oriented programming 1. Static data membersIn a class, a member can also be declared as a static data member, and in object-oriented programming, the Static keyword has new functionality. Let's start with an example:
C++test.cpp: Defines the entry point for a console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;


Class Statictest
{
private:
	//Here is declared, declaring a static member variable static
	int count;
	int id;
Public:
	statictest (int i): ID (i)
	{
		count++;
	}

	void Show ()
	{
		cout<< "ID:" <<id<<endl;
	}

	static void Showcount ()
	{
		cout<< ' Count: ' <<count<<endl;
	}
};

Define and initialize static member variables outside of the class, and you cannot define
int statictest::count = 0 in the class declaration because you need to allocate space for the definition;


int _tmain (int argc, _tchar* argv[])
{

	statictest test1 (1);
	Statictest test2 (2);
	Test1. Show ();
	Test2. Show ();
	Statictest::showcount ();

	System ("pause");
	return 0;
}

Result: id:1
Id:2
Count:2
Please press any key to continue ...

There are several things about static member variables: 1 static member variables have only one copy in a class, shared by all objects of the class, and static data members are allocated only one memory at a time. A non-static member variable is one copy of each object. 2 static member variables follow public,private,protected access rule 3) static data members allocate memory in the global data area and are shared by all objects in this class, but it does not belong to any object, so static member variables can be used even if no objects are generated. 4 static member variable initialization is more special, not directly like ordinary member variables in the class to give initial value, but not as a non-member variable as direct initialization, static member variables need to be declared in the class definition, and then class outside, with < type >< class name >::< variable name > = < value > format to initialize. As in the example above: int statictest::count = 0; 5 There are two ways to access static member variables, one of which is to access the normal member variable,< object name >.< static data member >. The other is a static member variable-specific way < class name >::< static data member >



2. Static member function

Or the above example, added a part of the function:

C++test.cpp: Defines the entry point for a console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;


Class Statictest
{
private:
	//Here is declared, declaring a static member variable static
	int count;
	int id;
Public:
	statictest (int i): ID (i)
	{
		count++;
	}

	void Show ()
	{
		//But non-static member functions can access static member functions and variable
		cout<< "ID:" <<id<< "  Count:" << count<<endl;
	}

	static void Showcount ()
	{
		//static member functions cannot access non-static members, nor can non-static member functions.
		//cout<< "ID:" <<id<<endl;     Error C2597: Illegal reference to non-static member "Statictest::id"
		//show ();:                    error C2352: "statictest::show": illegal invocation
		of non-static member functions cout<< "Count:" <<count<<endl;
	}
};

Define and initialize static member variables outside of the class, and you cannot define
int statictest::count = 0 in the class declaration because you need to allocate space for the definition;


int _tmain (int argc, _tchar* argv[])
{

	statictest test1 (1);
	Statictest test2 (2);
	Test1. Show ();
	Test2. Show ();
	Statictest::showcount ();

	System ("pause");
	return 0;
}

Results:

Id:1 Count:2
Id:2 Count:2
Count:2
Please press any key to continue ...


Where static member functions are noted:

1 static member functions can access static member functions and static member variables. However, static member functions cannot access ordinary member variables and normal member functions. (because the static member function does not have this pointer, it belongs to the shared)

2 non-static member functions can access static member variables and static member functions.

3 static member functions defined outside the class cannot be added statically, and static can be added at the time of the declaration, as defined by the normal member function.

4 static member functions are consistent with the calling rules of static member variables, and can be invoked without the need for an object. You can use the normal method, or you can use the class name:: Call.






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.