1.static类成员
C++primer里面说过,static类成员不像普通的类数据成员,static类数据成员独立于一切类对象处在。static类数据成员是与类关联的,
但不与该类定义的对象有任何关系。即static不会像普通类数据成员一样每一个类对象都有一份,全部类对象是共享一个static类成员的。
例如A类对象修改了static成员为1,那么B对象对应的static类对象成员的值也会是1。
static 成员不占用类对象的空间

#include <iostream> using namespace std; class A{ public: A(){} ~A(){} private: static int x; //static int x=1;错误 static void m_data(int a) { x=a; } }; int A::x=1; int main() { A my_class; cout<<sizeof(my_class)<<endl; return 0; }
注意:static类对象必须要在类外进行初始化
class Text { public: static int count; }; int Text::count=0;//用static成员变量必须要初始化 int main() { Text t1; cout<<t1.count<<endl; return 0; }//程序输出0
static修饰的变量先于对象存在,所以static修饰的变量要在类外初始化。因为static是所有对象共享的变量,必须要比对象先存在。
class Text { public: static int count; }; int Text::count=0;//用static成员变量必须要初始化 int main() { Text t1; Text t2; t1.count = 100; //t1对象把static成员count改为100 cout<<t2.count<<endl; //当t2对象打印static成员的时候,显示的是100而不是0 return 0; }
2.static类成员函数
由于static修饰的类成员属于类,不属于对象,因此static类成员函数是没有this指针的,this指针是指向本对象的指针。正因为没有this指针,所以static类成员函数
不能访问非static的类成员,只能访问 static修饰的类成员。
class Text { public: static int fun() { return num; } static int count; int num; }; int Text::count=5;//用static成员变量必须要初始化 int main() { Text t1; Text t2; t1.num=100; t1.fun();//发生错误,fun函数return的是非static类成员 如果return count就正确 return 0; }
调用方法:
(1)通过类对象调用
(2)通过类名调用
#include <iostream> using namespace std; class Account{ public: static double m_rate; // 声明:独立于类的对象之外 static void set_rate(const double& x){ m_rate=x; } }; double Account:: m_rate=1.0; // 设初始化,设初值(定义:获得内存) int main() { Account::set_rate(5.0); //类名调用 cout<<Account::m_rate<<endl; Account a; a.set_rate(7.0); // 对象调用静态成员函数,编译器将不再会在参数里添加this指针,这个隐含的操作 cout<<Account::m_rate<<endl; return 0; }