c++中的静态引用
references in c++ with 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吗?也能解释一下静态关键字
在计算机编程中,静态变量是静态分配的变量,其生存期或"范围"延伸到程序的整个运行过程。
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
相关文章:
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 类 Referention 中C++回调函数引用非静态函数
- Qt 静态库未定义引用
- 非静态成员引用必须相对于特定对象
- 引用静态数据成员
- 初始化类C++私有属性(值/引用/静态)
- 如何在类静态成员中引用静态变量?
- 从Visual Studio 2017引用静态库有多简单?
- C++:引用静态库的静态库
- C++未定义的引用(静态成员)
- 无法获取库上的枚举(未定义的引用静态元对象)
- 取消引用静态变量时的链接错误
- 未定义的引用静态成员C++
- "Undefined reference"尝试引用静态字段
- 引用静态函数作为类定义的一部分是否有任何开销?
- 未定义的引用静态函数指针成员在c++,我做错了什么
- 未定义的引用静态成员变量
- 未定义的引用静态成员
- 如何从另一个类的结构中引用静态成员变量
- 本例中引用静态变量的引用返回是否安全?