在面向对象程序设计中,成员变量(有时称为成员字段)是与特定对象相关联的变量,并且特定对象的所有方法(成员函数)均能访问該變量。
例子
C++
class Foo {
int bar; // Member variable
public:
void setBar(const int newBar) {
bar = newBar;
}
};
int main () {
Foo rect; // Local variable
return 0;
}
Java
public class Program
{
public static void main(String[] args)
{
// This is a local variable. Its lifespan
// is determined by lexical scope.
Foo foo;
}
}
public class Foo
{
/* This is a member variable - a new instance
of this variable will be created for each
new instance of Foo. The lifespan of this
variable is equal to the lifespan of "this"
instance of Foo
*/
int bar;
}
Python
class Foo:
def __init__(self):
self._bar = 0
@property
def bar(self):
return self._bar
@bar.setter
def bar(self, new_bar):
self._bar = new_bar
f = Foo()
f.bar = 100
print(f.bar)
Common Lisp
(defclass foo () (bar))
(defvar f (make-instance 'foo))
(setf (slot-value f 'bar) 100)
(print (slot-value f 'bar))
Ruby
/*
Ruby has three member variable types: class, class instance, and instance.
*/
class Dog
# The class variable is defined within the class body with two at-signs
# and describes data about all Dogs and their derived Dog breeds (if any)
@@sniffs = true
end
mutt = Dog.new
mutt.class.sniffs #=> true
class Poodle false
p.has_manners? #=> false
PHP
foo = $foo;
}
}
// Create a new Example object.
// Set the "foo" member variable to 5.
$example = new Example(5);
// Overwrite the "foo" member variable to 10.
$example->foo = 10;
// Prints 10.
echo $example->foo;
Lua
--region example
--- @class example_c
--- @field foo number Example "member variable".
local example_c = {}
local example_mt = {__index = example_c}
--- Creates an object from example.
--- @return example_c
function example_c.new(foo)
-- The first table argument is our object's member variables.
-- In a Lua object is a metatable and its member variables are table key-value pairs.
return setmetatable({
foo = foo
}, example_mt)
end
--endregion
-- Create an example object.
-- Set the "foo" member variable to 5.
local example = example_c.new(5)
-- Overwrite the "foo" member variable to 10.
example.foo = 10
-- Prints 10.
print(example.foo)
参考文献
评论 (0)