const and static keywords (definition, purpose) in C++

1. Definition and use of static

Static function: Control the storage method and visibility of variables
1. Modify local variables:
Usually local variables are stored in the stack area in the program. The local life cycle will end when the containing statement block is executed. Use the static keyword to modify local variables. Finally, the variable will store the static data area, and its life cycle will continue until the end of the entire program.
But the scope has not changed, and the scope is still limited to other statement blocks.
Personal understanding: static modifies local variables, which can be considered as local variables that extend the life cycle of the variable (it will not end with the function but is released)
2. Modify global variables:
For a global variable, it can be accessed in this file , and can also be accessed from other source files in the same project (just add extern for declaration). Using static to modify the global variable changes its scope, from the original visibility of the entire project to the visibility of this file.
3. Modified function:
Like global variables, it changes the scope and limits its use to this file.
4. Modified class:
Modifying a function in the class means that the function belongs to a class, not any object of this class;
modifying a variable in the class means that the variable is owned by all objects, and there is only one copy in the storage space. , can be called through classes and objects.
(Supplement: Static non-const data members can only be defined and initialized outside the class, and can only be declared within the class.)
The sample is as follows;

5: Class member/class function declaration
The scope of the static variable in the function body is the function body. Different from the auto variable, the memory of this variable is only allocated once, so its value will still maintain the last value the next time it is called; in the
module Static global variables within the module can be accessed by functions within the module, but cannot be accessed by other functions outside the module;
static functions within the module can only be called by other functions within the module, and the scope of use of this function is limited to Within the module in which it is declared;
the static member variables in the class are owned by the entire class, and there is only one copy of all objects of the class; the
static member functions in the class are owned by the entire class, and this function does not receive this pointer, so However, only static member variables of the class can be accessed. Static class objects must be initialized outside the class. Variables modified by static exist before the object, so variables modified by static must be initialized outside the class. Since
class members modified by static belong to the class and not the object, static class member functions There is no this pointer, which is a pointer to this object. Because there is no this pointer, static class member functions cannot access non-static class members, but can only access static-modified class members; static member functions cannot be virtual-modified
. Static members do not belong to any object or instance, so adding virtual has no practical meaning; static member functions do not have this pointers, the implementation of virtual functions is to allocate a vptr pointer to each object, and vptr is called through this pointer , so it cannot be virtual; the calling relationship of virtual function is this->vptr->ctable->virtual function.

class Person
{
    
    
public:
	Person(string name,int age)
	{
    
    
		this->m_name = name;
		this->m_age = age;
	}
  //静态函数
   	static void func()
	{
    
    
		//m_age = 50;   静态函数只能访问静态变量
		m_score = 99;
		cout << m_score << endl;
	}
  
	string m_name;
	int m_age;
   //静态成员变量   类内声明
	static int m_score; 
};

int Person::m_score = 100; //静态变量 类外初始化

int main()
{
    
    
	Person p1("张三" , 18);
	Person p2("李四", 20);

	cout << "成绩 " << p1.m_score << endl; //通过类对象访问
	p2.m_score = 80; //静态变量 只有一个副本,一个内存空间
	cout<< "成绩 " << p2.m_score << endl; 
  
  //静态函数调用
	Person::func();    // 通过类调用
	p1.func();         //通过类对象调用
 
	return 0;
}

2. Definition and use of const

The role of const: Limit readability
1. const modifies the basic data type.
Const has the same result before and after the basic data type. The value of the constant cannot be changed when using these constants. The modifier const can be used before or after the type specifier, and the result is the same. When using these constants, just do not change the values ​​of these constants.

const int Max = 100;
int const Min = 1;

void demo()
{
    
    
	//Max = 110; 常量不可修改
	//Min = 2;   常量只读性
	cout << Max << Min << endl;
}

2. Modify pointer variables and reference variables.
If const is on the left side of *, then const modifies the variable pointed by the pointer, that is, the pointer points to a constant.

If const is on the right side of *, const modifies the pointer itself, that is, the pointer itself is a constant.

int a = 10, b = 20;

//使 指针指向常量   (指针指向可改 ,指向的值不可以更改)
const int* p1 = &a;  
p1 = &b;
//*p1 = 100;              错误用法

 //使 指针本身为常量  (指针指向不可改 ,指向的值可以更改)
int* const p2 = &b; 
//p2 = &a;              错误用法
*p2 = 100;

3. Const modifies ordinary functions
to prevent the parameters passed in from being changed in the function body, but it is only meaningful for pointers and references. Because if it is passed by value, what is passed to the parameter is only a copy of the actual parameter. Even if the formal parameter is changed in the function body, the actual parameter will not be affected. like:

void func(const int i)
{
    
    
	//i = 10;  不能修改i
	cout << i << endl;
}

When the function parameter modified by const is a pointer, it means that the content pointed by the pointer cannot be modified in the function body, which plays a protective role:

void fun(const char * src, char * des)
{
    
      
  //保护源字符串不被修改,若修改src则编译出错。
	strcpy(des,src);
}

const Modify function return value
Use const to modify the returned pointer or reference to protect the content pointed by the pointer or the content of the reference from being modified.

//const 修饰函数返回值 
const int* getNum(int* a)
{
    
    
	return a;
}

int a = 10;
auto ret= getNum(&a);
//ret = 20  返回值不能修改

4. Usage of const in classes:
const member variables are constants only during the life cycle of an object. Can be changed for the entire class. Because a class can create multiple objects, different objects can have different const data member values. Therefore, const data members cannot be initialized in the declaration of the class, because the compiler does not know the value of the const data member before the class object is created. The initialization of const data members can only be done in the initialization list of the constructor of the class. .

const member function:
The main purpose of const member function is to prevent the member function from modifying the contents of the object. It should be noted that the const keyword and the static keyword cannot be used at the same time for member functions, because the static keyword modifies a static member function that does not contain this pointer, that is, the const member function cannot be instantiated and must be specific to a certain function.

Constant object:
A constant object can only call constant functions, and no other member functions can be called.

Supplement: If you really want to modify a variable in a const member function, you can use mutable to modify it. If you want to create a constant in the member variable that is constant throughout the class, you should use the enumeration constant in the class or static const.

class Person
{
    
    
public:
	Person(string name,int age)
	{
    
    
		this->m_name = name;
		this->m_age = age;
	}

	//常函数
	void func() const
	{
    
    
		m_sore = 100;

	}
	//普通成员函数
	void Print()
	{
    
    
		cout << "姓名: " << this->m_name << "  年纪:" << this->m_age << end;
	}
	string m_name;
	int m_age;
	mutable int m_sore =60;  //特殊变量
};

int main()
{
    
    
	const Person p("张三", 18);  // 常对象

	//常对象调用常函数
	p.func();
	//p.Print();  常对象只能调用常函数
	
	p.m_sore = 160;   //m_sore 为特殊变量只能在常对象下修改
	cout << p.m_sore << endl;

	system("pause");
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_52302919/article/details/132319184