// 类的友元.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#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; }//隐藏有this指针,指向当前使用的对象,其实是return this->x;
int getY() { return y; }
friend float dist(Point &a, Point &b);//友元函数是非成员函数,不属于Point类
private:
int x, y;
};
//友元函数的定义
float dist(Point& a, Point& b) {//若将形参改为const类型,则编译器报错,显示不能访问私有数据成员
double x = a.x - b.x;//在友元函数内部可以直接调用类的对象的私有成员
double y = a.y - b.y;
return float(sqrt(x*x + y * y));
}
int main()
{
Point p1(1, 1), p2(4, 5);
cout << "the distance is:";
cout << dist(p1, p2) << endl;
cout << p1.getX() << p1.getY() << endl;
cout << sizeof(p1) << endl;
return 0;
}
参考清华大学郑莉C++程序设计
C++之友元函数
最新推荐文章于 2024-07-10 08:55:20 发布