成员变量或字段与全局变量之间有什么区别?概念是否相同?
答案 0 :(得分:3)
成员变量在类的范围内声明。除非它是静态的,否则该类的每个对象都会有一个不同的变量副本。
全局变量在任何类的范围之外声明,可以在任何函数中使用。程序中只有一份副本。
#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;
}