- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
Chapterten运算符重载重点
Author: J. de Wet Lecture 10: Operator Overloading (运算符重载) Chapter Ten:Operator Overloading (运算符重载) Use of friend (使用友元) The need for operator overloading(运算符重载的必要性) Rules of operator overloading(运算符重载的规则) Overloading operators(重载运算符) shallow copy and deep copy (浅拷贝和深拷贝) friend friend是C++提供的一种破坏数据封装和数据隐藏的机制。 通过将一个模块声明为另一个模块的友元,一个模块能够引用到另一个模块中本是被隐藏的信息。 可以使用友元函数和友元类。 为了确保数据的完整性,及数据封装与隐藏的原则,建议尽量不使用或少使用友元。 friend function 友元函数是在类声明中由关键字friend修饰说明的非成员函数,在它的函数体中能够通过对象名访问 private 和 protected成员 作用:增加灵活性,使程序员可以在封装和快速性方面做合理选择。 访问对象中的成员必须通过对象名。 use friend function calculating the distance of two points #include iostream #include cmath using namespace std; class Point //Point类声明 { public: //外部接口 Point(int xx=0, int yy=0) {X=xx;Y=yy;} int GetX() {return X;} int GetY() {return Y;} friend double Distance(Point a, Point b); private: //私有数据成员 int X,Y; }; double Distance( Point a, Point b) { double dx=a.X-b.X; double dy=a.Y-b.Y; return sqrt(dx*dx+dy*dy); } int main() { Point p1(3.0, 5.0), p2(4.0, 6.0); double d=Distance(p1, p2); coutThe distance is dendl; return 0; } 1、将普通函数声明为友元函数 #includeiostream using namespace std; class time { public: time(int ,int,int ); friend void display(time ); private: int hour; int minute; int sec; }; 2.友元成员函数 #includeiostream using namespace std; class date; class time { public: time(int ,int,int ); void display(date ); private: int hour;int minute;int sec; }; class date { public: date(int ,int,int); friend void time:: display(date ); private: int month; int day; int year; }; time::time(int h,int m,int s) friend class If a class for another kind of friend, this kind of all members access to another class private members. 声明语法:将友元类名在另一个类中使用friend修饰说明。 friend class example class A { friend class B; public: void Display() {coutxendl;} private: int x; }; class B { public: void Set(int i);
您可能关注的文档
最近下载
- 交通银行真题及答案(可下载).doc VIP
- 《建筑节能与可再生能源利用通用规范》.pdf VIP
- GZ067 智能节水系统设计与安装赛项正式赛卷模块A 评分标准-2023年全国职业院校技能大赛赛项正式赛卷.docx VIP
- 高标准农田建设项目施工组织设计 .pdf VIP
- TPM课件完整版本.ppt VIP
- 河北秦皇岛职业技术学院选聘专任教师考试真题2024.docx VIP
- 学堂在线《临床中成药应用》作业单元考核答案.docx VIP
- 三国两晋南北朝的政权更迭与民族交融ppt课件.pptx VIP
- 围墙护栏制作与安装工程检验批质量验收记录.docx VIP
- 2025年甘肃省张掖市辅警考试题库(附答案).docx VIP
文档评论(0)