(一)定义:友元函数是指某些虽然不是成员却能够访问类的所有成员的函数。类授予它的友元特别的访问权。通常同一个开发者会出于技术和非技术的原因,控制类的友元和成员函数(否则当你想更新你的类时,还要征得其它部分的拥有者的同意)。

(二)使用非友元函数将两个对象中的变量进行相加

 #include <iostream>
#include <string.h>
#include <unistd.h> using namespace std; class Point {
private:
int x;
int y; public:
Point() {}
Point(int x, int y) : x(x), y(y) {} int getX(){ return x; }
int getY(){ return y; }
void setX(int x){ this->x = x; }
void setY(int y){ this->y = y; }
void printInfo()
{
cout<<"("<<x<<", "<<y<<")"<<endl;
}
}; Point add(Point &p1, Point &p2)
{
Point n;
n.setX(p1.getX()+p2.getX());
n.setY(p1.getY()+p2.getY());
return n;
} int main(int argc, char **argv)
{
Point p1(, );
Point p2(, ); Point sum = add(p1, p2);
sum.printInfo(); return ;
}

(三)使用友元函数进行两个对象中变量的相加

 #include <iostream>
#include <string.h>
#include <unistd.h> using namespace std; class Point {
private:
int x;
int y; public:
Point() {}
Point(int x, int y) : x(x), y(y) {} int getX(){ return x; }
int getY(){ return y; }
void setX(int x){ this->x = x; }
void setY(int y){ this->y = y; }
void printInfo()
{
cout<<"("<<x<<", "<<y<<")"<<endl;
}
friend Point add(Point &p1, Point &p2);
}; Point add(Point &p1, Point &p2)
{
Point n;
n.x = p1.x+p2.x;
n.y = p1.y+p2.y;
return n;
} int main(int argc, char **argv)
{
Point p1(, );
Point p2(, ); Point sum = add(p1, p2);
sum.printInfo(); return ;
}

最新文章

  1. 如何在Infraworks中创建多树种组成的森林
  2. 为什么Web 设计会‘死’?
  3. Memcache安全配置
  4. datagridview 右键选中行 并弹出菜单
  5. 关于MANIFEST.MF的理解
  6. DEDE站点从网站根目录移到子目录
  7. 8 个实用的 Linux netcat 命令示例
  8. 超强1000 JQuery插件
  9. mysql基础之存储引擎
  10. 前端基础之HTML
  11. Java虚拟机-内存tips
  12. 使用Builder模式创建复杂可选参数对象
  13. c/c++再学习:C与Python相互调用
  14. 20165237 2017-2018-2 《Java程序设计》第7周学习总结
  15. Android源码分析二 硬件抽象层(HAL)
  16. SAP的软件维护费用,交还是不交?
  17. Linux shell 菜鸟学习笔记....
  18. python: ImportError: cannot import name &#39;Style&#39; from &#39;openpyxl.styles&#39; 解决方法
  19. 『转』VC++ webbrowser函数使用范例
  20. js实现简单拖拽效果

热门文章

  1. Vue起飞前的准备
  2. PHP的 parse_ini_file 解析配置文件
  3. javascript 写一个ajax 自动拦截,并下载数据
  4. 【SQL Server DBA】日常巡检语句3:特定监控(阻塞、top语句、索引、作业)
  5. Android Studio 代码页跳界面 /java和XML快速切换技巧
  6. java 框架-分布式文件管理系统1FastDFS
  7. Xamarin开发综述
  8. 微信小程序 上传图片并等比列压缩到指定大小
  9. BPM软件_财务报销流程管理解决方案_K2工作流引擎
  10. 服务器去掉IE浏览器网络安全限制