普通成员变量:通过对象名访问、不能对象间共享
可定义静态成员变量和静态成员函数,静态成员为整个类所有,不依赖任何对象,可通过类名或对象名访问public静态成员,静态成员函数可直接访问静态成员变量
类的静态成员变量存储位置与全局变量、静态局部变量同,在全局数据区
静态成员变量不依赖于任何对象,需在类外单独分配空间,语法Type ClassName::VarName
class Test
{
private:
static int cI;
public:
static int GetI()
{
return cI;
}
static void SetI(int i)
{
cI = i;
}
void print()
{
printf("cI = %d\n", cI);
}
};
int Test::cI; //默认值为0
int main()
{
Test::SetI(5);
printf("Test::cI = %d\n", Test::GetI()); //5
Test t1,t2;
t1.print(); //5
t2.print(); //5
t1.SetI(10);
t2.print(); //10
printf("Test::cI = %d\n", Test::GetI()); //10
return 0;
}
从命名空间角度看,类的静态成员只是该类命名空间内的全局变量和全局函数,不同之处是,类可对静态成员进行访问权限限制,而命名空间不行从面向对象角度看,类静态成员属于类概念本身,类所有对象共享相同静态成员
class Test //统计对象创建个数
{
private:
static int cCount;
public:
static int GetCount()
{
return cCount;
}
Test()
{
cCount++;
}
~Test()
{
cCount--;
}
};
int Test::cCount;
void run()
{
Test ta[100];
printf("%d\n", Test::GetCount()); //102,返回时局部变量被销毁
}
int main()
{
Test t1,t2;
printf("%d\n", Test::GetCount()); //2
run();
printf("%d\n", Test::GetCount()); //2
return 0;
}
------/静态成员函数与普通成员函数区别class c3
{
int i;
int j;
short k;
short l;
static int c;
public:
void print()
{
}
};
int c3::c;
int main()
{
printf("%d\n",sizeof(c3)); //12
return 0;
}
类对象成员变量和成员函数分开存储,普通成员变量存储于对象中,与struct变量有相同内存布局和字节对齐方式,静态成员变量存储于全局数据区中,成员函数存储于代码段中class从面向对象理论出发,将变量和函数定义在一起,用于描述现实世界中的类,而从计算机角度看,程序依然由数据段和代码段构成
编译器如何完成面向对象理论到计算机程序的转化?
静态成员函数与普通成员函数区别:静态成员函数不包含指向具体对象的指针,普通成员函数包含指向具体对象的指针
普通成员函数都隐式包含一个指向当前对象的this指针
#include <stdio.h>
class Test
{
int i;
int j;
int k;
static int c;
public:
Test(int i, int j, int k)
{
this->i = i; //不加this,随机值
this->j = j;
this->k = k;
}
void print()
{
printf("Object Address: %08X\n", this);
printf("&c = %08X, c = %d\n", &c, c);
printf("&i = %08X, i = %d\n", &i, i);
printf("&j = %08X, j = %d\n", &j, j);
printf("&k = %08X, k = %d\n", &k, k);
}
static void print() //报错,静态成员函数无this指针
{
printf("%08X\n", this);
}
};
int Test::c;
int main()
{
Test t1(0, 1, 2);
Test t2(3, 4, 5);
printf("t1 Address: %08X\n", &t1);
t1.print();
printf("t2 Address: %08X\n", &t2);
t2.print();
return 0;
} //this与相应对象及i,三者地址同