static修饰类数据成员
#include "stdafx.h"
#include <iostream>
using namespace std;
#if 0
static 在类内部的表现,用来实现族类对象间的数据共享,static类成员不像普通的类数据成员,static
类数据成员独立于一切类对象存在,static类数据成员是与类关联的,但不与该类定义的对象有任何关系
就是static不会像普通类数据成员一样每个对象都有单独的一份,全部类对象共享一个static类成员
在生成对象的时候,普通数据成员才有空间。
而static成员 在类声明的时候,就已经开辟了空间
开辟在data段的rw段,它存储在静态区,占用全局的内存,和全局变量分配的内存在同一个区域里
所以它不占用类对象的内存
static 数据成员 既属于类,也属于对象,但终归属于类。
因为在没有对象的时候 可以通过类来访问
类其实本质上也是一个命名空间 static数据成员相当于类中的全局变量
初始化 不能加static
类内定义,类外初始化。 type 类名::变量名 = 初值
因为static类型的变量是类级别的,不能随着对象的创建而申请内存,所以需要单独的进行类外定义
在定义的时候C++编译器会申请内存给静态指针
#endif
namespace Space
{
int share = 111;
}
class A
{
public:
void func()
{
cout << share << endl;
}
void modify(int m)
{
share = m; //更改
}
int x; int y;
static int share; //不占空间
};
//share为public 可以直接调用
int A::share = 100; //初始化时一定不能加static
int _tmain(int argc, _TCHAR* argv[])
{
#if 0
A a, b, c;
//static数据成员不占空间
cout << "sizeof(A)= " << sizeof(A) << endl;
cout << "sizeof(a)= " << sizeof(a) << endl;
cout << "sizeof(b)= " << sizeof(b) << endl;
cout << "sizeof(c)= " << sizeof(c) << endl;
a.func(); //如果 share没有初始化会错误
A a, b, c;
a.func();
a.modify(2000); //对static的数据发生更改
b.func();
c.func();
#endif
cout << A::share << endl; //属于类
A a;
a.func(); //也属于对象
cout << Space::share << endl;
return 0;
}
static const修饰数据成员
#include "stdafx.h"
#include <iostream>
using namespace std;
#if 0
正常const数据成员在构造参数列表中初始化
正常static数据成员在 类外面初始化
而 static const(也可以是const static)数据成员直接就地初始化
static const 数据成员和成员函数 在public情况下
可以不用对象调用 直接用类调用
#endif
class A
{
public:
static const void dis() //管理static const数据成员的成员函数
{
cout << i << endl;
}
private:
static const int i=8; //在此初始化
};
int _tmain(int argc, _TCHAR* argv[])
{
A::dis();
//cout << A::i << endl; i为public情况下
return 0;
}