C++ 友元函数

友元函数是在类中用关键字friend修饰的非成员函数。友元函数可以是一个普通的函数,也可以是其他类的成员函数,虽然它不是本类的成员函数,但是在它的函数体中可以通过对象名访问类的私有和保护成员。

#include <iostream>
#include <cmath>

using namespace std;

class Point {
	private:
		int x, y;      // 私有数据成员 
	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);  // 友元函数声明
}; 

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));  // static_cast是一个c++运算符,功能是把一个表达式转换为float类型。
}

int main(){
	Point *point1 = new Point(1, 1);  // 定义 Point 类的对象 
	Point *point2 = new Point(4, 5);   // 定义 Point 类的对象 
	
	cout << "两点间的距离是:";
	cout << dist(*point1, *point2) << endl;  // 计算两点间的距离 
	
	delete point2;
	delete point1;
	
	return 0;
}

注:友元函数不仅可以是一个普通函数,也可以是另一个类的成员函数。友元成员函数的使用和一般友元函数的使用基本相同,只是要通过相应的类或对象名来访问。

#include<iostream>

using namespace std;

class girl{
	private:
	    char name;
	    int age;
	    
	public:
	    girl(char n, int d){     //构造函数
	        name = n;
		    age = d;
		}
		
		friend void display(girl &x);  //声明友元函数
};

void display(girl &x){    //类外定义 友元函数
    cout << "姓名:" << x. name << "\n年龄:" << x.age << endl;
    //girl类的友元函数能访问girl类对象的私有成员
}

int main(){
    girl e('z', 18);
    display(e); //调用友元函数
	         
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值