C++笔记 友元函数,友元类,运算符重载
来源:互联网 发布:淘宝字体侵权 编辑:程序博客网 时间:2024/05/09 11:52
1 友元函数
在友元函数中可以访问私有属性
class A{ friend void modify_i(A *p,int a);private: int i;public: A(int i){ this->i = i; } void myprint(){ cout << i << endl; }};//友元函数的实现,在友元函数中可以访问私有的属性void modify_i(A *p,int a){ p->i = a;}void main(){ A *a = new A(10); a->myprint(); modify_i(a,20); a->myprint(); system("pause");}
void main(){ A *a = new A(10); a->myprint(); modify_i(a,20); a->myprint(); system("pause");}
通过在类中定义友元函数,然后在外部实现,通过访问这个实现的友元函数,就可以访问类中的私有属性。
打印结果
1020
2 友元类
class A{ //友元类 friend class B;private: int i;};class B{public: //B这个友元类可以访问A类的任何成员 void accessAny(){ a.i = 30; }private: A a;};
3 运算符重载
class Point{public: int x; int y;public : Point(int x = 0,int y = 0){ this->x = x; this->y = y; } void myprint(){ cout << x << ","<<y<< endl; }};//重载+号Point operator+(Point &p1,Point &p2){ Point tmp(p1.x + p2.x, p1.y + p2.y); return tmp;}
void main(){ Point p1(10,20); Point p2(20,10); Point p3 = p1 + p2; p3.myprint(); system("pause");}
打印结果
30,30
4 成员函数 运算符重载
class Point{public: int x; int y;public: Point(int x = 0, int y = 0){ this->x = x; this->y = y; } Point operator+(Point &p2){ Point tmp(this->x+p2.x,this->y+p2.y); return tmp; } void myprint(){ cout << x << "," << y << endl; }};
void main(){ Point p1(10,20); Point p2(20,10); Point p3 = p1 + p2; //p1.operator+(p2); 运算符重载,本质还是函数的调用 p3.myprint(); system("pause"); }
打印结果
30,30
5 当属性私有时 通过友元函数完成运算符重载
class Point{ friend Point operator+(Point &p1, Point &p2);private: int x; int y;public: Point(int x = 0, int y = 0){ this->x = x; this->y = y; } Point operator+(Point &p2){ Point tmp(this->x + p2.x, this->y + p2.y); return tmp; } void myprint(){ cout << x << "," << y << endl; }};Point operator+(Point &p1,Point &p2){ //此处可以访问p.x Point tmp(p1.x + p2.x, p1.y + p2.y); return tmp;}
void main(){ Point p1(10, 20); Point p2(20, 10); Point p3 = p1 + p2; p3.myprint(); system("pause");}
打印结果
30,30
阅读全文
0 0
- C++笔记 友元函数,友元类,运算符重载
- 【c++】关于类继承运算符重载友元函数
- 运算符重载与友元函数
- c++ 运算符重载 友元函数
- 利用友元函数,重载运算符
- 友元函数重载运算符
- 运算符重载为友元函数
- 重载运算符以及友元函数
- 7.10友元函数重载运算符
- 运算符重载和友元函数
- 友元函数编写运算符重载
- 友元函数编写运算符重载
- C++ 重载运算符 友元函数
- C++运算符重载,友元函数
- 友元函数以及重载运算符
- 友元函数和运算符重载
- 重载运算符与友元函数
- 运算符重载和友元函数
- React Native WebView组件实现的BarCode(条形码)、(QRCode)二维码
- 阅读ISE源码过程中重新对单例模式的理解
- Java开发中的23种设计模式详解----解释器模式(Interpreter)
- maven项目构建struts2框架项目遇到的org.apache.jasper.JasperException: Unable to compile class for JSP:
- JAVAWEB开发之Hibernate详解(三)——Hibernate的检索方式、抓取策略以及利用二级缓存进行优化、解决数据库事务并发问题
- C++笔记 友元函数,友元类,运算符重载
- WPF控件之TabItem
- tensorflow 移植到android平台
- 企业模板:瓷器玉石文化收藏品类织梦模板
- 北京大型电商招聘:架构部总监(70-100w)
- Tempter of the Bone
- 安装与使用 Spark-jobServer
- Javascript学习笔记
- idea 一个多maven项目聚合