static与成员变量,成员函数

1.成员变量 

 static修饰成员后创建的对象都共享一个静态成员。static修饰的静态成员变量只能在类内部定义,类外初始化

class Person {
public:
    int _age;
    static int height;
};

int Person::height = 166;

class Person{
};
Person p;
cout<<sizeof(p)<<endl;

当类内为空时输出1;

class Person {
public:
    int _age;
	int  _score;
};

有两个int型时sizeof(p) = 8

class Person {
public:
    int _age;
	int  _score;
    static int height;
};

两个int数据再加static修饰的成员变量时所占字节数不改变。

static修饰的成员变量存储在类的外部,计算类的大小时不包含在内。

2.成员函数 

static修饰的成员函数,同静态变量一样可以通过对象或类调用。(普通成员函数只能通过对象调用)

class Person {
public:

 static void show() {
    cout << "这是静态成员函数" << endl;

}

}

Person::show;//通过类直接调用

const + static 可以做到既共享又被保护不改变。

class Person {
private:
    const static int height;
};
const int Person::height = 180;

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值