C ++和Java中的静态变量 [英] Static variables in C++ and Java

查看:162
本文介绍了C ++和Java中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题:
让我们有这个函数:(在C ++中)

I have a question: lets say we have this function: (in C++)

int& f(){static int x = 0; return x;} // OK

int& h(){int x=0; return x;} // ERROR

为什么 h 给出错误?是因为关键字 static ?我发现 static 关键字让我的 x 变量在我的函数被终止后生存。所以我仍然在外面的那个内存位置(另一个函数或main?right?)访问ACC。 h x = 0 / code>终止。对?我不知道我真的有这个!

Why h gives an error? Is it because of the keyword static? I found static keyword lets my x variable live after my function is terminated. So I still cann acces at that memory location from the outside (another function or main? right?) Instead int x =0 is lost after h terminates. Right? I'm not sure i really got it!

而Java呢?我红了,我不能del68 static 方法中的变量,但只能在类。

And What about Java? I red I cannot delcare static variables in methods but only in Classes.

谢谢。 b $ b

推荐答案

在C ++中, static 是语言中最重载的关键字之一。您在此处使用的含义是:

In C++, static is one of the most overloaded keywords of the language. The meaning you're using here is this:

static 说明符中定义在函数中的变量具有静态存储持续时间 - 它占用程序的整个运行时的相同空间,并且保持其在对函数的不同调用之间的值。因此,您可以安全地返回一个引用,因为变量总是存在于引用中。

A variable which is defined inside a function with the static specifier has static storage duration - it occupies the same space for the entire runtime of the program, and keeps its value between different calls to the function. So you can safely return a reference to it, as the variable is always there to back the reference.

正常(非 - static )函数局部变量在函数调用返回时被销毁,因此引用变为悬挂 - 它不引用任何有效的。使用它会导致未定义的行为。

A normal (non-static) function-local variable is destroyed when the function call returns, and so the reference becomes dangling - it doesn't refer to anything valid. Using it results in Undefined Behaviour.

Java简单地没有函数范围 static t具有关键字 static 的含义。

Java simply doesn't have function-scope static variables (it doesn't have that meaning of the keyword static). That's why you can't declare it there.

C ++和Java都具有 static 关键字。当一个类的成员用 static 关键字声明时,它意味着成员不绑定到类的任何实例,而是一个全局变量,其标识符存在于类的范围。

Both C++ and Java have the "class-scope" meaning of the static keyword. When a member of a class is declared with the static keyword, it means the member is not bound to any instance of the class, but is just a global variable whose identifier lives in the class's scope.

这篇关于C ++和Java中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆