#include<iostream>
#include<cmath >
using namespace std;
class point
{
public://接口
point(int xx = 0, int yy = 0) ://制作一个点并计数
x(xx), y(yy)
{
count++;
}
int getx() { return x; }
int gety() { return y; }
void num()
{
cout << "点的个数为:" << count<<endl;
}
friend float dist(const point &a, const point& b);//友元授权
private:
int x, y;
static int count;
};
int point:: count = 0;//静态变量要这样初始化
float dist(const point &a, const point &b)//一个计算两个点距离的函数;
{
double x = a.x - b.x;
double y = a.y - b.y;
return static_cast<float>(sqrt(x * x + y * y));
}
int main()
{
point p1(1, 2);
point p2(4, 7);
cout << "两点的距离为:" << dist(p1, p2) << endl;
p1.num();
return 0;
}
类中的静态变量
类中的静态变量用static定义,为该类的所有对象所共有
例如可以定义一个记录对象个数的静态变量,在构造和赋值构造对象时使其加1,在析构时使其减去。
static int count;
int point:: count = 0;//静态变量要这样初始化
point(int xx = 0, int yy = 0) ://制作一个点并计数
x(xx), y(yy)
{
count++;
}
若是分开文件(类的定义和类中函数的说明不在一个问件)那么用到静态变量时前面要加 类名::
类的友元
如果这个类没有对象,我们如何访问其中的静态变量?
(如果类有对象,我们可以以对象为桥梁,调用自定义函数访问其私有静态变量)
友元是c++提供的一种破坏数据封装和数据隐藏的机制
可以声明友元函数和友元类
在定义类时要给友元函数授权,且友元函数要有参数
friend float dist(point &a, point& b);//友元授权,用引用使用这个对象效率高点;
float dist(point &a, point &b)//一个计算两个点距离的函数;
{
double x = a.x - b.x;//直接访问a和b中的x和y;
double y = a.y - b.y;
return static_cast<float>(sqrt(x * x + y * y));
}
也可以直接把另一个类作为友元,这样子友元类可以直接访问他的私有成员,友元类的方向时单向的;
共享数据的保护
1定义常对象:
在定义的时候初始化,且不能被更新: const 类名 对象名
const point p1(1, 2);
2常成员:用const来修饰的成员(const 可以作为重载函数的区分)
如果时const类对象,会调用重名函数中有const修饰的那个
void print();
void print()const;//编译器认真审查函数体,不改变参数的值
3常引用:
被引用的对象不能更新:const 类型说明符&引用名
friend float dist(const point &a, const point& b);//友元授