c_cpp 静态变量,函数,引用和所有东西,它们表现得非常复杂。这个要点试图尝试这些概念

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 静态变量,函数,引用和所有东西,它们表现得非常复杂。这个要点试图尝试这些概念相关的知识,希望对你有一定的参考价值。

#include<iostream>
using namespace std;

int &fun()
{
	static int x = 10;
	return x;
}
int main()
{
	fun(); // Will initialize the static integer inside fun()
  // A static variable once defined stays in memory till the end of the program
  // Only thing is that its scope stays inside the function. 
  // But if we can copy its reference then we can use it anywhere
	cout << fun() << endl; // Prints 10 
	int &x = fun(); // Gets reference to the static variable
	x = 100; // Modifies the reference. This should modify the static variable too
	cout << fun() << endl; // Verifying if static variable was modified or not 
  // It outputs 100 and that means we were right.
	return 0;
}

// This function will throw complation error because int x inside this function 
// gets removed as soon as the function call is completed and hence returning
// a reference of x doesn't make sense. 
int &fun2(){
  int x = 10;
  return x;
}

/*
OUTPUT
10
100
*/
#include<iostream>
using namespace std;
 
int main()
{
   int *ptr = NULL;
   int &ref = *ptr; // We are initializing the reference. 
   cout << ref;
}

// At run time ref will be referencing to NULL and hence it will
// give a segmentation fault

以上是关于c_cpp 静态变量,函数,引用和所有东西,它们表现得非常复杂。这个要点试图尝试这些概念的主要内容,如果未能解决你的问题,请参考以下文章

java中静态方法,静态变量,静态初始化器,构造函数,属性初始化都是啥时候调用的? 它们的先后顺序。

c++中对静态变量的未定义引用

PHP中静态变量和函数引用返回

java:在java中为啥静态变量没有this引用?

静态成员变量和静态成员函数(C++)

[C++] 智能指针的引用计数如何实现?—— 所有该类的对象共享静态类成员变量