带有静态的c ++中的引用

时间:2015-08-27 22:42:29

标签: c++ reference static

以下是输出问题。我无法理解为什么答案是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并且还可以解释静态关键字的作用

3 个答案:

答案 0 :(得分:3)

  

在计算机编程中,静态变量是一个静态分配的变量 - 其生命周期或“范围”在整个程序运行中延伸

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

}

答案 1 :(得分:1)

static使变量在函数调用中保持不变。

这意味着static int x = 10;首次调用func时会执行一次。

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

现在,你需要了解什么是参考。要了解什么参考,你需要了解指针。我猜你会很容易找到解释这两个的网站。

答案 2 :(得分:1)

案例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;
}

这里,在call fun()中,我们声明了一个局部变量int x,一旦从fun()返回就会超出范围。 所以,在行cout << fun()中声明了一个新变量,并返回了新变量的地址。

案例2:

static int x = 10;    

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

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