c++中的静态引用

references in c++ with static

本文关键字:引用 静态 c++      更新时间:2023-10-16

下面是一个输出问题。我不明白为什么它的答案是30。

#include<iostream>
using namespace std;                     //namespace std is being used                      
int &fun()
{                            
    static int x = 10;                   //x is static
    return x;
}
int main()
{
    fun() = 30;
    cout << fun();           //fun() called
    return 0;
}

输出:30有人能告诉我为什么输出是30吗?也能解释一下静态关键字

的作用吗?

在计算机编程中,静态变量是静态分配的变量,其生存期或"范围"延伸到程序的整个运行过程。

void foo()
{
    int a = 10;
    static int b = 10;
    a++;
    b++;
    std::cout << "a : " << a << " , b : " << b << std::endl;
}

引用变量是别名,即已经存在的变量的另一个名称。一旦用变量初始化了引用,就可以使用变量名或引用名来引用该变量。

int a = 4;
int b = a;
int &c = a;
c++;
std::cout << "b = " << b << std::endl; //4
std::cout << "a = " << a << std::endl; //5
std::cout << "c = " << c << std::endl; //5
/* Becaues c is a refence to a, it means that
a and c are just different names to the same memory location
so updating either one updates the actual value in memory
*/
a++;
std::cout << "c = " << c << std::endl;  //6
std::cout << "a = " << a << std::endl;  //6
//consider the function below:
int &bar()
{
    static int a = 5;
    std::cout << "a is " << a << std::endl;
    return a;
}

测试两者:

int main()
{
    for (int i = 0; i < 3; i++)
        foo();
    //for every call of foo():
    //memory allocation for a is created and deleted when a goes out of scope
    //memoery allocation for b extends through out the life of the program
   //bar() returns a reference to "a" i.e
   int reference_to_a = bar(); //prints 5
   reference_to_a = 30; 
   bar();  //prints 30
   bar() = 50;  //prints 30 and later assigns 50 to the reference returned.
   bar();       //prints 50
}

static使变量在函数调用中持续存在

表示func第一次被调用时,static int x = 10;将被执行一次。

int static_test()
{
    static int x = 10;
    x++;
    return x;
} 
static_test(); // first call will return 11
static_test(); // second call will return 12 because the value of x ( was saved and was then incremented)
static_test(); // third call will return 13

现在,您需要了解什么是引用。为了理解什么是引用,你需要理解指针。我猜你会很容易找到一些网站解释这两个

case 1:

#include<iostream>
using namespace std;                     //namespace std is being used                      
int &fun()
{                            
    int x = 10;                   //x is static
    return x;
}
int main()
{
    fun() = 30;
    cout << fun();           //fun() called
    return 0;
}

这里,在fun()调用中,我们声明了一个局部变量int x,一旦它从fun()返回,它就会超出作用域。因此,在cout << fun()行声明了一个新变量,并返回了新变量的地址。

案例2:

static int x = 10;    
这里的

,因为变量'x'是静态的,它只能初始化一次。即,第一次将x初始化为5,然后重写为30。

现在,当您在随后的时间进行函数调用时,static int x = 5被忽略。因此,它返回值30