本文共 1485 字,大约阅读时间需要 4 分钟。
将要共享的数据说明为类的静态成员。静态成员是指声名为static
的类的成员,包括静态数据成员和静态成员函数,在类的范围内所有对象共享该数据
静态数据成员不属于任何对象,它不因对象的建立而产生,也不因对象的析构而删除,是类的一部分。
特点:<数据类型><类名>::<变量名> = <初值>
#includeusing namespace std;class Point{ public: static int point_count; Point(int x = 0, int y = 0); ~Point();private: int _x; int _y;};Point::Point(int x , int y ){ _x = x; _y = y; point_count++; cout<<"Constructor"; cout<<"Point_Num = "< <
静态成员函数的定义和其他成员函数一样,静态成员函数与静态数据成员类似,属于类本身。在函数定义前加static
关键字。
#includeusing namespace std;class Point{ public: Point(int x = 0, int y = 0); ~Point(); static void show_count();private: int _x; int _y; static int point_count;};void Point::show_count(){ cout<<"Point Num = "< <
有时候需要普通函数直接访问一个类的保护或者私有数据成员。友元是C++提供给外部的类或者函数访问类的私有成员和保护成员的另一种途径。友元可以是一个函数,称为友元函数,也可以是一个类,称为友元类。
在类里声名一个普通函数,加上关键字friend
,就成了该类的友元函数,它可以访问该类的一切成员。
friend <类型><函数名>(参数)
#include#include using namespace std;class Point{ public: Point(int x = 0, int y = 0); ~Point(); friend double pointDistance(const Point a,const Point b); static void show_count();private: int _x; int _y; static int point_count;};void Point::show_count(){ cout<<"Point Num = "< <
一个类也可以被声明为类一个类的友元,该类称为友元类。
假设有类A,类B,在类B的定义中将类A声名为友元,那么类A被称为类B的友元类,它所有的成员函数都可以访问类B中的任意成员。转载地址:http://jnrx.baihongyu.com/