C++之友元函数

// 类的友元.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++程序设计
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值