1.静态生存期
对象的生存期与程序的运行期相同,则称它具备静态生存期。
[细节]定义时未指定初值的基本类型静态生存期变量,会被赋予0来初始化,而动态生存期变量不指定初值意味着初值时随机数。ios
2.静态变量特色
不随每次函数调用产生一个副本,也不随函数返回而失效,实现数据共享。函数
3.举例子引出问题
关于一个公司有多少人员的问题,若是问公司的A和B,他们说的答案应该是同样的,但是要怎么用代码来实现这种数据的一致性呢,这就须要用到静态成员。测试
#include<iostream> using namespace std; class Point { public: Point(int x = 0, int y = 0) :x(x), y(y) { count++; } Point(Point &p) { x = p.x; y = p.y; count++; } ~Point() { count--; } int getX() { return x; } int getY() { return y; } void showCount() { cout << " Object count is " << count << endl; } private: int x, y; static int count;//静态数据成员变量 }; int Point::count = 0; //静态数据成员定义和初始化用类名限定,它在对象被建立以前就已经存在,因此不用构造函数来初始化 int main() { Point a(4, 5);//构造函数被调用count=1 cout << "Point A: " << a.getX() << ";" << a.getY(); a.showCount(); Point b(a);//复制构造函数被调用,count在原基础上进行自加,count=2 cout << "Point B:"<<b.getX() <<";"<<b.getY(); b.showCount(); return 0; }
代码结果
4.静态函数成员
声明:static 函数返回值类型 函数名(参数表) ;
静态成员函数能够直接访问该类的静态数据和函数成员,而访问非静态成员,必须经过对象名。spa
calss A { public: static void f(A a); private: int x; }; void A::f(A a) { cout<<x;//错误 cout<<a.x;//正确 }
1.定义
数据成员值在对象的整个生存周期内不能被改变。
常对象必须初始化,不能被更新code
const int n=1; n=3;//错,不能对常量赋值
2.常成员函数
声明:类型说明符 函数名(参数表)const;
一个对象若为常对象,则经过该对象只能调用它的常成员函数; 不管是否经过常对象调用常成员函数,在常成员函数调用期间,目的对象都被视为常对象。
3.实例与测试对象
#include<iostream> using namespace std; class R { public: R(int r1,int r2):r1(r1),r2(r2) { } void print(); void print()const;//常成员函数 private: int r1, r2; }; void R::print() { cout << r1 << " ; " << r2<<endl; } void R::print()const//区别于上一个输出函数 { cout << r1 << " ; " << r2; cout << " function of const is calling" <<endl; } int main() { R a(4, 5); a.print(); const R b(20, 25); b.print();//调用常成员函数 return 0; }
代码结果
blog