您的位置:首页 > 其它

第12周-项目1(2)

2016-05-17 13:23 405 查看
问题及代码:

/*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)一个类的成员函数也可以作为另一个类的友元,但必须先定义这个类。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: