Variables “a”与“a”之间的区别;成员变量";或;“字段”;及;全局变量";
成员变量或字段与全局变量之间的区别是什么?概念相同吗?成员变量在类的范围内声明。除非它是静态的,否则该类的每个对象都会有一个不同的变量副本 全局变量在任何类的作用域之外声明,可以从任何函数中使用。程序中只有一个副本 示例代码Variables “a”与“a”之间的区别;成员变量";或;“字段”;及;全局变量";,variables,global-variables,Variables,Global Variables,成员变量或字段与全局变量之间的区别是什么?概念相同吗?成员变量在类的范围内声明。除非它是静态的,否则该类的每个对象都会有一个不同的变量副本 全局变量在任何类的作用域之外声明,可以从任何函数中使用。程序中只有一个副本 示例代码 #包括 使用std::cout; 使用std::endl; const int global_var=1;//全局变量的定义。 结构示例{ 公众: static int static_member_var;//一个静态成员变量。 const static int const
#包括
使用std::cout;
使用std::endl;
const int global_var=1;//全局变量的定义。
结构示例{
公众:
static int static_member_var;//一个静态成员变量。
const static int const_static_member_var;//这些只是声明。
int member_var;//一个非静态成员变量。
//此类型的每个对象都有自己的成员_var,而所有
//此类型的对象将共享其静态成员。
};
int-example\u-t::static\u-member\u-var=0;
const int示例\u t::const\u static\u member\u var=global\u var;
//我们可以在这里使用全局变量。这两者在同一时间内只存在一次
//程序,并且必须有一个定义。超出了我们的工作范围
//声明了这些,我们必须给它们的范围来引用它们。
内部主(空)
{
示例a,b;//两个不同的示例结构。
a、 成员_var=2;
b、 成员_var=3;//这些是不同的。
a、 静态成员变量=5;
//这是引用它的另一种方式。因为b有相同的变量,所以
//两者都改变了。
//我们也可以使用main()中的全局变量。
你可以在谷歌上输入同样的内容,看看为什么谷歌是最好的!你认为我没有这样做吗?没有答案不能让我满意。这就是我在这里问这个问题的原因。1)你没有标记你所问的语言,这使你的问题更广泛。2)当你说你不满意时,你到底对哪一部分感到困惑第3节)你的问题太广了,很可能很快就要关闭了。你需要问一些你不满的具体问题。谢谢,但是一个例子是很好的,你没有用任何语言来标记这个词,所以我会用C++。现在,它已经写了。java的规则稍微不同,但是它是基于C++的,非常相似。在我的示例中,s全局变量更像“静态成员变量”。感谢您提供了一个很好的示例
#include <iostream>
using std::cout;
using std::endl;
const int global_var = 1; // The definition of the global variable.
struct example_t {
public:
static int static_member_var; // A static member variable.
const static int const_static_member_var; // These are just declarations.
int member_var; // A non-static member variable.
// Every object of this type will have its own member_var, while all
// objects of this type will share their static members.
};
int example_t::static_member_var = 0;
const int example_t::const_static_member_var = global_var;
// We can use global_var here. Both of these exist only once in the
// program, and must have one definition. Outside the scope where we
// declared these, we must give their scope to refer to them.
int main(void)
{
example_t a, b; // Two different example_t structs.
a.member_var = 2;
b.member_var = 3; // These are different.
a.static_member_var = 5;
// This is another way to refer to it. Because b has the same variable, it
// changes it for both.
// We can use global_var from main(), too.
cout << "global_var is " << global_var
<< ", example_t::const_static_member_var is " << example_t::const_static_member_var
<< ", b.static_member_var is " << b.static_member_var
<< ", a.member_var is " << a.member_var
<< " and b.member_var is " << b.member_var
<< "." << endl;
return 0;
}