1 友元函数、友元类
友元关系是单向的,下例:B是A的友元,B可以单向访问A类的private成员和protected成员,A不能访问B。
友元函数可以是其他类的成员函数。
注意,A类的友元需在A中定义。
class A{
friend class B;
...}
class B{
}
#include <iostream>
#include <cmath>
using namespace std;
class Point { //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 static_cast<float>(sqrt(x * x + y * y));
}
int main() { //主函数
Point myp1(1, 1), myp2(4, 5); //定义Point类的对象
cout << "The distance is: ";
cout << dist(myp1, myp2) << endl; //计算两点间的距离
return 0;
}
2 const
- const int &a :常引用-**只读的引用;**用常引用做参数,既有效率也有保密性。非内部数据类型采用此方式比较好,内部数据类型(int、float等)的参数不存在构造、析构的过程,而复制也非常快,“值传递”和“引用传递”的效率几乎相当。
- const也是区分重载函数的因素之一(还有参数类型、参数数量)
- 常函数:void print() const ,
const表示一种承诺,即“我不会改变对象的状态”,对于不打算改变对象状态的函数,可以声明为常函数。 - 常函数可以处理普通对象、常对象;但普通函数不能处理常对象。
- 常成员 const int a / static const int a