【翁恺】06-成员变量

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  表示该成员变量是属于对象的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

理心炼丹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值