第12周-项目1(2)
2016-05-17 13:23
405 查看
问题及代码:
运行结果:
知识点总结:
关于友元函数(百度百科):
1)必须在类的说明中说明友元函数,说明时以关键字friend开头,后跟友元函数的函数原型,友元函数的说明可以出现在类的任何地方,包括在private和public部分;
2)注意友元函数不是类的成员函数,所以友元函数的实现和普通函数一样,在实现时不用"::"指示属于哪个类,只有成员函数才使用"::"作用域符号;
3)友元函数不能直接访问类的成员,只能访问对象成员,
4)友元函数可以访问对象的私有成员,但普通函数不行;
5)调用友元函数时,在实际参数中需要指出要访问的对象,
6)类与类之间的友元关系不能继承。
7)一个类的成员函数也可以作为另一个类的友元,但必须先定义这个类。
/*Copyright (c)2016,烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:main.cpp *作 者:王艺霖 *完成日期:2016年5月17日 *版 本 号:v1.0 *问题描述:请用类的友元函数,而不是成员函数,再次完成上面提及的运算符的重载; *输入描述: *输出描述: */ #include <iostream> using namespace std; class Complex { public: Complex(){real=0;imag=0;} Complex(double r,double i){real=r; imag=i;} friend Complex operator+(Complex &c1,Complex &c2); friend Complex operator-(Complex &c1,Complex &c2); friend Complex operator*(Complex &c1,Complex &c2); friend Complex operator/(Complex &c1,Complex &c2); void display(); private: double real; double imag; }; //下面定义成员函数 Complex operator+(Complex &c1,Complex &c2) { Complex c; c.real=c1.real+c2.real; c.imag=c1.imag+c2.imag; return c; } Complex operator-(Complex &c1,Complex &c2) { Complex c; c.real=c1.real-c2.real; c.imag=c1.imag-c2.imag; return c; } Complex operator*(Complex &c1,Complex &c2) { Complex c; c.real=c1.real*c2.real-c1.imag*c2.imag; c.imag=c1.imag*c2.real+c1.real*c2.imag; return c; } Complex operator/(Complex &c1,Complex &c2) { Complex c; c.real=(c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); c.imag=(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); return c; } void Complex::display() { cout<<"("<<real<<","<<imag<<"i)"<<endl; } //下面定义用于测试的main()函数 int main() { Complex c1(3,4),c2(5,-10),c3; cout<<"c1="; c1.display(); cout<<"c2="; c2.display(); c3=c1+c2; cout<<"c1+c2="; c3.display(); c3=c1-c2; cout<<"c1-c2="; c3.display(); c3=c1*c2; cout<<"c1*c2="; c3.display(); c3=c1/c2; cout<<"c1/c2="; c3.display(); return 0; }
运行结果:
知识点总结:
关于友元函数(百度百科):
1)必须在类的说明中说明友元函数,说明时以关键字friend开头,后跟友元函数的函数原型,友元函数的说明可以出现在类的任何地方,包括在private和public部分;
2)注意友元函数不是类的成员函数,所以友元函数的实现和普通函数一样,在实现时不用"::"指示属于哪个类,只有成员函数才使用"::"作用域符号;
3)友元函数不能直接访问类的成员,只能访问对象成员,
4)友元函数可以访问对象的私有成员,但普通函数不行;
5)调用友元函数时,在实际参数中需要指出要访问的对象,
6)类与类之间的友元关系不能继承。
7)一个类的成员函数也可以作为另一个类的友元,但必须先定义这个类。
相关文章推荐
- bzoj4591 [Shoi2015]超能粒子炮·改
- Android环境搭建
- POJ 2104 K-th Number 划分树
- 互联网秒杀业务架构设计 / 秒杀系统架构分析与实战
- C#与C++(结构体内对象指定大小)
- ios app打ipa包
- 详解Office 外接程序 COM Add In的LoadBehavior及其妙用
- LoadRunner下设置监控Windows系统资源
- Unity AssetDatabase和Resources资源管理
- iOS --统一导航栏“返回”键,并当push隐藏控制器底部tabBar
- 中文编译提示 Code::Blocks SVN6988学习增强版(适合C/C++初学者)
- KMP算法与next数组的代码初步实现
- 【HYSBZ1588: [HNOI2002]】营业额统计——伸展树
- 深入JDK源码_Index --> 深入JDK源码之ThreadLocal类 --> 陶邦仁 又发现一牛人
- z-index的有关注意事项
- IntelliJ IDEA 显示行号和设置字体大小的方法
- Asp.Net Mvc 使用WebUploader 多图片上传
- Ehcache详细解读
- 利用 NGINX 最大化 Python 性能,第二部分:负载均衡和监控
- 解决LINUX 双网卡无法上网问题小记