常引用是只读的引用
#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(const Point &p1,const Point &p2);
private:
int x,y;
};
//常引用只能读取变量,不能修改变量
float dist(const Point &p1, const Point &p2){
// p1.x = 1; //cannot assign to variable 'p1' with const-qualified type 'const Point &'
double x = p1.x - p2.x;
double y = p1.y - p2.y;
//强制类型转换操作符,static_cast使用位截断进行处理
return static_cast<float>(sqrt(x*x+y*y));
}
int main()
{
//常量
const Point myp1(1,1),myp2(4,5);
cout << "The distance is :";
cout << dist(myp1,myp2) << endl;
return 0;
}