C++(三十四) — 友元函数、友元类
2024-10-06 06:29:05
友元是可以访问类的私有成员和保护成员的外部函数。由 friend 修饰,不是本类的成员函数,但是在它的函数体中可以通过对象名访问本类的私有和保护成员。
友元关系不可传递,且是单向的。
友元函数:声明为友元的一般函数或是另一个类的成员函数;
友元类:友元类的所有成员函数都是某个类的友元函数。应用场景较少。
1、友元函数
应用于运算符重载多一些。
#include <iostream>
#include <cmath>
using namespace std; //友元函数举例
class Point {
public:
Point(int xx = , int yy = )
{
X = xx; Y = yy;
}
int GetX() { return X; }
int GetY() { return Y; }
friend float fDist(Point &a, Point &b);
private:
int X, Y;
};
//友元函数的实现
float fDist(Point &p1, Point &p2)
{
//通过对象访问私有数据成员
double x = double(p1.X - p2.X);
double y = double(p1.Y - p2.Y);
return float(sqrt(x*x + y*y));
}
void main()
{
Point myp1(, ), myp2(, );
cout << "The distance is: ";
cout << fDist(myp1, myp2) << endl;
system("pause");
}
2、友元类
应用较少,了解即可。
#include <iostream>
using namespace std; class A {
public:
friend class B;//在 B类中可以访问 A类 的私有成员、私有函数。 // 友元类声明的位置和 public/private 没有关系。
friend void modifyA(A *pA, int _a); //该函数是 类A 的好朋友
A(int a=, int b=)
{
this->a = a;
this->b = b;
}
int getA()
{
return this->a;
}
private:
int a, b;
}; void modifyA(A *pA, int _a)
{
pA->a = _a;
}
//友元类使用场景较少
class B
{
public:
void Set(int a)
{
Aobject.a = a;
}
void printB()
{
cout << Aobject.a << endl;
}
private:
A Aobject;
};
void main()
{
A a1(, );
cout << a1.getA() << endl;
modifyA(&a1, );
cout << a1.getA() << endl; B b1;
b1.Set();
b1.printB();
system("pause");
}
最新文章
- mvc上传到云虚拟机的问题解决
- Oracle 11g 7个压缩包说明
- matlab函数集锦
- 用JS实现回文数的精准辨别!!!
- 第3组UI组件:AdapterView及其子类
- java中小工具&mdash;&mdash;&mdash;&mdash;UUID
- Java内部类——局部内部类
- Winfrom 文本框回车进入下一个个单元格(TextBox)
- 数字图像处理(MATLAB版)学习笔记(1)——第1章 绪言
- zabbix 网络模板自动发现端口时,过滤掉某些特定规则的端口,减少item的方法
- oracle存储过程出现ORA-01403: 未找到数据 问题解决方法
- java面试中经常会被问到分布式面试题
- 菜鸟教程之工具使用(二)——Maven打包非规范目录结构的Web项目
- HDU1565_方格取数(1)
- loj6436【PKUSC2018】神仙的游戏
- CCF CSP 201503-2 数字排序
- 使用Node.js 搭建http服务器 http-server 模块
- 前端PHP入门-024-字符串函数-API查看
- 23SpringMvc_各种参数绑定方式-就是<;input那种
- org.springframework.beans.factory.BeanCreationException: Error creating bean with name &#39;supplierAction&#39;: Injection of resource dependencies failed; nested exception is org.springframework.beans.factor