目录
C++中的静态成员与this指针
一、静态成员
1、static 关键字
- 静态属性只能在全局范围内进行初始化赋值
- 静态方法可以直接通过类名进行访问,也可以通过对象名进行访问
class Teacher {
private:
char* name;
public:
//计数器
static int total;
public:
Teacher(char* name) {
this->name = name;
cout << "Teacher有参构造函数" << endl;
}
~Teacher() {
cout << "Teacher析构函数" << endl;
}
void setName(char* name) {
this->name = name;
}
char* getName() {
return this->name;
}
//计数的静态函数
static void count(){
total++;
cout << "total:" << total << endl;
}
};
//静态属性初始化赋值
int Teacher::total = 10;
void main() {
Teacher::total++;
cout << Teacher::total << endl;
//直接通过类名访问
Teacher::count();
cout << Teacher::total << endl;
//通过对象名访问
Teacher t1((char*)"JACK");
t1.count();
cout << Teacher::total << endl;
getchar();
}
二、类的大小
C/C++ 内存分区:栈、堆、全局(静态、全局)、常量区(字符串)、程序代码区
普通属性与结构体具有相同的内存布局
class A {
public:
int i;
int j;
int k;
};
class B {
public:
int i;
int j;
int k;
void myprint() {
cout << "打印" << endl;
}
};
void main() {
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
getchar();
}