c++第三次作业
类的静态成员
静态数据成员
如果某个属性为整个类所共有,不属于任何一个具体的对象,则可以采用static关键字来声明为静态成员。如果将“类”比作一个工厂,对象就是工厂生产的产品,静态成员就是存放在工厂中、属于工厂的,而不是属于每个产品的。
静态数据成员具有静态生存期,即静态数据成员生存期与程序运行期相同。
访问时需要用“类名::标识符”来访问静态数据成员。(注:静态数据成员的初始化要在类定义之外在加以定义)
例如:
#include<iostream> using namespace std; class Point { public: Point(int x = 0, int y = 0): x(x), y(y)//构造函数 { count++;//在构造函数中对count累加,所有对象共同维护同一个count } Point(Point& p)//复制构造函数 { x = p.x; y = p.y; count++; } int getx() { return x; } int gety() { return y; } void showcount() { cout << " object count=" << count << endl; } private: int x, y; static int count;//静态数据成员,用于记录点的个数 }; int Point::count = 0;//静态数据成员定义和初始化,用类名限定 int main() { Point a(4, 5);//定义对象a,其构造函数会使count+1 cout << "point a:" << a.getx() << "," << a.gety() << endl; a.showcount(); Point b(a);//定义对象b,其复制构造函数会使count+1 cout << "point b:" << b.getx() << "," << b.gety() << endl; b.showcount(); return 0; }
运行结果:
静态函数成员
静态数据函数就是使用static关键字声明的函数成员。静态成员函数也属于整个类,由同一个类的所有对象共同拥有,为这些对象共享。
静态成员函数可以通过类名或对象名来调用,而非静态成员函数只能通过对象名来调用。
静态成员函数可以直接访问该类的静态数据和函数成员。而访问非静态成员,必须通过对象名。
例如:
class A { public: static void f(A a); private: int x; }; void A::f(A a) { cout << x; //对x的引用是错误的 cout << a.x; //正确 }
一般情况下,静态成员函数主要用来访问同一个类中的静态数据成员,维护对象之间共享的数据。
例如:
#include<iostream> using namespace std; class Point { public: Point(int x = 0, int y = 0): x(x), y(y)//构造函数 { count++;//在构造函数中对count累加,所有对象共同维护同一个count } Point(Point& p)//复制构造函数 { x = p.x; y = p.y; count++; } int getx() { return x; } int gety() { return y; } static void showcount()//静态函数成员 { cout << " object count=" << count << endl; } private: int x, y; static int count;//静态数据成员,用于记录点的个数 }; int Point::count = 0;//静态数据成员定义和初始化,用类名限定 int main() { Point::showcount();//输出对象个数的初始值 Point a(4, 5);//定义对象a,其构造函数会使count+1 cout << "point a:" << a.getx() << "," << a.gety() << endl; Point::showcount(); Point b(a);//定义对象b,其复制构造函数会使count+1 cout << "point b:" << b.getx() << "," << b.gety() << endl; Point::showcount(); return 0; }
运行结果:
与上一段程序相比,运用静态函数成员的好处是可以不依赖与任何对象,直接访问静态数据。