local variable
-
local variables are defined inside a method,have a scope limited to the method to which they belong
-
a local variable of the same name as a field will prevent the filed being accessed form within a method
和c类似,重名时本地变量会屏蔽成员变量
fields,parameters,local variables
-
all three kinds of variable are able to store a value that is appropriate to their defined type
-
fields are defined outside constructors and methods
-
fields are used to store data that persists(持续) throughout the life of an object.as such,they maintain the current state of object.they have a lifetime that lasts as long as their objects lasts.
-
fields have class scope:their accessibility extends throughout the whole class,and so they can be used within any of the constructor methods of the class in which they are defined
field :成员变量
parameters:函数的参数
local variable:本地变量
a.h
class A{
private:
int i; // 成员变量, 声明而不是定义
public:
void f();
};
a.cpp
#include "a.h"
void A::f(){
int j = 10; // 本地变量,只在f中有效
i=20; // 成员变量,所有类的成员函数中可以使用
}
int main(){
A a; // 成员变量i在a中
a.f(); // 使用的是 a 的i
A b; // 成员变量i在b中
return 0;
}
成员变量不在类里面, 在类的每个对象里面。有了对象后才有了成员变量。
成员变量的秘密
parameters:函数的参数 和 local variable:本地变量 是相同的东西。都是本地存储,在函数内部有效。都会放在栈的地方,但有不同。
field :成员变量在哪里?声明只是说明有这个东西,但是不知道在哪里。成员变量写到类的声明里面,并不知道在哪里。成员变量在类的成员函数中就可以使用,不用考虑它们在哪里。它们在类的每个对象里面。目前一般来说,类是概念,没有变量。
函数是属于类的,不是属于对象的。所有对象用到的函数是同一个。但是成员变量是和对象绑定的。
(形同C语言中:要修改结构中的变量将结构的的地址作为函数的参数传入函数中---指针的方式----c++类中隐藏的参数=>this)
c++中所有的机制都是通过c语言实现的
call functions in a class
Point a; a.print();
- there is a relationship with the function be called and the variable calls it
- the function itself knowns it is doing something with the variable
this: the hidden parameter
-
this is a hidden parameter for all member functions,with the type of the class
void Point::pint() ->(can be regarded as) void Point::print(Point *p)
this 是一个关键字,是一个指针,类型是该函数所属的类的对象的指针。默认是可以隐藏不写的。
函数定义中对于成员变量 i = 20 等价于 this -> i = 20 表示该成员变量是属于对象的。