静态数据成员
·用关键字static声明
·当声明类的数据成员为静态时,无论创建多少个类的对象,静态成员都只有一个副本
·在类的所有对象中共享,具有静态生存期
·若不存在其他的初始化语句,在创建第一个对象时,所有的静态数据成员被初始化为零
·在类外定义和初始化,用范围解析运算符(::)来指明所属的类
举例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # 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;
}
~Box() { count --; }
private :
double length, width, height;
};
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 指针,可以使用静态成员函数来判断类的某些对象是否已被创建
·用静态成员函数访问非静态成员,需通过对象
举例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | # 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 指针
使用静态成员了解构造与析构函数的调用情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | # include <iostream>
using namespace std;
class A {
friend class B;
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" ;
}
void set(int m, int n);
void displayB();
~B() {
cout << "调用析构\n" ;
}
private :
A mpt1, mpt2;
};
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();
return 0;
}
|
登录后复制
相关文章:
C++静态成员与常成员的使用
C++复习要点总结之五静态成员变量及成员函数
以上是C++类的静态数据成员和静态成员函数的详细内容。更多信息请关注PHP中文网其他相关文章!