静态数据成员
用static声明该类的所有对象维护该成员的同一个拷贝
必须在类外定义和初始化,用(::)来指明所属的类
可用对象名访问也可以用类名访问
静态成员函数
类外代码可以使用类名和作用域操作符来调用静态成员函数
静态成员函数只能引用属于该类的静态数据成员或者静态成员函数
#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; }
static void showCount() {
cout << "Object number:" << count << endl;
}
private:
int x, y;
static int count;
};
int Point::count = 0;
int main() {
Point::showCount();
Point a(4, 5);
cout << "a" << a.getX() << ":" << a.getY() << endl;
a.showCount();
Point b(a);
cout << "b" << b.getX() << ":" << b.getY()<< endl;
a.showCount();
}
结果:
Object number:0
a4:5
Object number:1
b4:5
Object number:2
请按任意键继续. . .
友元函数
在类内声明用friend,不是类内成员。
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
public:
Point(int x = 0, int y = 0) :x(x),y(y){}
int getX() { return x; }
int getY() { return y; }
friend float dist(Point&p1, Point&p2); //友元函数声明
private:
int x, y;
};
float dist(Point&p1, Point&p2) { //友元函数定义
double x = p1.x - p2.x;
double y = p1.y - p2.y;
return sqrt(x*x + y*y);
}
int main() {
Point p1(1, 1);
Point p2(4, 5);
cout << dist(p1, p2) << endl;
}
结果:
5
请按任意键继续. . .
友元类
单向的 ,不具有传递性,不可派生。谁是谁的友元类必须写出来,a是b的友元类,a可以访问b的私有成员,b不可以访问a的私有成员。
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
public:
Point(int x = 0, int y = 0) :x(x),y(y){}
int getX() { return x; }
int getY() { return y; }
friend float dist(Point&p1, Point&p2);
friend class Line; //友元类声明
private:
int x, y;
};
class Line{ //友元类定义
public:
private:
};
float dist(Point&p1, Point&p2) {
double x = p1.x - p2.x;
double y = p1.y - p2.y;
return sqrt(x*x + y*y);
}
int main() {
Point p1(1, 1);
Point p2(4, 5);
cout << dist(p1, p2) << endl;
}