009_linuxC++之_友元函数
2024-09-05 04:15:35
(一)定义:友元函数是指某些虽然不是类成员却能够访问类的所有成员的函数。类授予它的友元特别的访问权。通常同一个开发者会出于技术和非技术的原因,控制类的友元和成员函数(否则当你想更新你的类时,还要征得其它部分的拥有者的同意)。
(二)使用非友元函数将两个对象中的变量进行相加
#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 ;
}
最新文章
- 如何在Infraworks中创建多树种组成的森林
- 为什么Web 设计会‘死’?
- Memcache安全配置
- datagridview 右键选中行 并弹出菜单
- 关于MANIFEST.MF的理解
- DEDE站点从网站根目录移到子目录
- 8 个实用的 Linux netcat 命令示例
- 超强1000 JQuery插件
- mysql基础之存储引擎
- 前端基础之HTML
- Java虚拟机-内存tips
- 使用Builder模式创建复杂可选参数对象
- c/c++再学习:C与Python相互调用
- 20165237 2017-2018-2 《Java程序设计》第7周学习总结
- Android源码分析二 硬件抽象层(HAL)
- SAP的软件维护费用,交还是不交?
- Linux shell 菜鸟学习笔记....
- python: ImportError: cannot import name &#39;Style&#39; from &#39;openpyxl.styles&#39; 解决方法
- 『转』VC++ webbrowser函数使用范例
- js实现简单拖拽效果