静态数据成员
·用关键字static声明
·当声明类的数据成员为静态时,不管建立多少个类的对象,静态成员都只要一个副本
·在类的一切对象中同享,具有静态生存期
·若不存在其他的初始化语句,在建立第一个对象时,一切的静态数据成员被初始化为零
·在类外定义和初始化,用局限剖析运算符(::)来指明所属的类
举例:
#include <iostream> using namespace std; class Box { public: static int count; //若该静态数据成员在private部份声明,则只能经由过程静态成员函数处置惩罚 Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout << "One constructor was called." << endl; length = l, width = b, height = h; count++; //每建立一个对象时加1 } double Volume() { return length * width * height; } ~Box() { count--; } private: double length, width, height; }; //初始化类Box的静态成员 int Box::count = 0; int main(void) { Box Box1(3.3, 1.2, 1.5); Box Box2(8.5, 6.0, 2.0); cout << "Total objects: " << Box::count << endl; //输出对象的总数 return 0; }
静态成员函数
把成员函数声明为静态的,就能够把函数与类的任何特定对象自力开来
·在类对象不存在的状况下也能被挪用,运用类名加局限剖析运算符 :: 即可接见
·静态成员函数只能接见静态成员数据、其他静态成员函数和类外部的其他函数
·静态成员函数有一个类局限,不能接见类的 this 指针,能够运用静态成员函数来推断类的某些对象是不是已被建立
·用静态成员函数接见非静态成员,需经由过程对象
举例:
#include <iostream> using namespace std; class Box { public: static int count; Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"One constructor was called." << endl; length = l, width = b, height = h; count++; } double Volume() { return length * width * height; } static int getCount() { //静态成员函数 return count; } private: double length, width, height; }; int Box::count = 0; int main(void) { //在建立对象之前输出对象的总数 cout << "Inital Stage Count: " << Box::getCount() << endl; Box Box1(3.3, 1.2, 1.5); Box Box2(8.5, 6.0, 2.0); //在建立对象以后输出对象的总数 cout << "Final Stage Count: " << Box::getCount() << endl; return 0; }
注:
静态成员函数与一般成员函数的区分:
·静态成员函数没有 this 指针,只能接见静态成员(包含静态成员变量和静态成员函数)
·一般成员函数有 this 指针,能够接见类中的恣意成员;而静态成员函数没有 this 指针
运用静态成员相识组织与析构函数的挪用状况
#include <iostream> using namespace std; class A { friend class B; //类B是类A的友元 public: static int value; static int num; A(int x, int y) { xp = x, yp = y; value++; cout << "挪用组织:" << value << endl; } void displayA() { cout << xp << "," << yp << endl; } ~A() { num++; cout << "挪用析构:" << num << endl; } private: int xp, yp; }; class B { public: B(int x1, int x2) : mpt1(x1 + 2, x2 - 2), mpt2(x1, x2) { cout << "挪用组织\n"; //mpt是类A的对象,有几个mpt,有关类A的操纵便实行频频 } void set(int m, int n); void displayB(); ~B() { cout << "挪用析构\n"; //析构函数在类完毕前挪用,类完毕的时刻开释类请求的空间 } private: A mpt1, mpt2; //将A类的对象声明为B类的私有数据成员 }; int A::value = 0; int A::num = 0; void B::set(int m, int n) { mpt1.xp = m * 2, mpt1.yp = n / 2; } void B::displayB() { mpt1.displayA(); } int main() { B p(10, 20); cout << "Hello world!" << endl; B displayB(); //经由过程友元,使类B输出类A的私有数据成员 return 0; }
相干文章:
C++静态成员与常成员的运用
C++温习要点总结之五静态成员变量及成员函数
以上就是C++类的静态数据成员和静态成员函数的细致内容,更多请关注ki4网别的相干文章!