第六周 项目六(3):复数模板类

来源:互联网 发布:文明6 mac 配置要求 编辑:程序博客网 时间:2024/05/16 15:42

问题及代码:

/** Copyright (c) 2015, 烟台大学计算机学院* All rights reserved.* 文件名称:friend.cpp* 作    者:李楠* 完成日期:2015年4月12日* 版 本 号:v1.0** 问题描述: 阅读教材例10.1。该例实现了一个复数类,但是美中不足的是,复数类的实部和虚部都固定只能是double型的。             可以通过模板类的技术手段,设计Complex,使实部和虚部的类型为定义对象时指定的实际类型。* 输入描述:(3)友元函数提供了一种非成员函数访问私有数据成员的途径,模板类使类中的数据成员的类型变得灵活,这两种技术可以结合起来用。             要求在前面方案的基础上支持用友员函数实现的加法。用于测试的main()函数如下:* 程序输出: 略*/#include<iostream>#include<cstring>using namespace std;template <class numtype>class Complex{public:    Complex (numtype a=0,numtype b=0):real(a),imag(b){};    Complex <numtype> complex_add(Complex<numtype> &c);    template <class numtype1> friend Complex <numtype1> add_complex(Complex<numtype1> &c,Complex<numtype1> &c1);//很疑惑~!!!!!    void display();private:    numtype real,imag;};template <class numtype>void Complex <numtype>::display(){    cout<<"("<<real<<","<<imag<<"i)"<<endl;}template <class numtype>Complex <numtype> Complex <numtype>::complex_add(Complex<numtype> &c)//相加{    Complex<numtype> c1;    c1.real=real+c.real;    c1.imag=imag+c.imag;    return c1;}template <class numtype>Complex <numtype> add_complex(Complex<numtype> &c,Complex<numtype> &c1)//相除{    Complex<numtype> c2;    c2.real=c1.real+c.real;    c2.imag=c1.imag+c.imag;    return c2;}int main( ){    Complex<int> c1(3,4),c2(5,-10),c3;    c3=c1.complex_add(c2);  //调用成员函数支持加法运算,有一个形参    cout<<"c1+c2=";    c3.display( );    Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6;    c6=c4.complex_add(c5);  //调用成员函数支持加法运算,有一个形参    cout<<"c4+c5=";    c6.display( );    Complex<int> c7;    c7=add_complex(c1,c2);  //调用友员函数支持加法运算,有两个形参    cout<<"c1+c2=";    c7.display( );    Complex<double> c8;    c8=add_complex(c4,c5);  //调用友员函数支持加法运算,有两个形参    cout<<"c4+c5=";    c8.display( );    return 0;}


运行结果:

 

知识点总结:

难道是我没好好听最后一个视频么!!!?类模板和友元函数的共同使用的格式真的没搞明白啊!!我还是好好再看看视频找找资料吧

学习心得:

人丑就要多读书…书中自有黄金屋…书籍是人类进步的阶梯…多看书多看书…

0 0
原创粉丝点击