c++运算符重载习题
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Task8-1
/*
1. 定义一个复数类 Complex ,重载运算符“ + ”,使之能用于复数的加法运算将运算符函数重载为非成员、非友元的普通函数。编写程序,求两个复数之和
*/
#include
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
void display();
double real;
double imag;
};
void Complex::display()
{
cout<<"("< } Complex operator +(Complex &c1,Complex & c2) { Complex p; p.real=c1.real+c2.real; p.imag=c1.imag+c2.imag; return p; } int mai n() { Complex c1(3,5),c2(2,5),c3; c1.display(); coutvv"+"; c2.display(); cout<<"="; c3=c1+c2; c3.display(); Task8-2 /*2. 定义一个复数类 Complex ,重载运算符“ + ”、”- “、” *”、” / ”,使之能用于复数的加、减、乘、除。运算符重载函数作为 Complex 类的成员函数,编程,分别求两个复数之和差积商。 */ #include using namespace std; class Complex {public: Complex(){real=0;imag=0;} Complex(double r,double i){real=r;imag=i;} Complex operator+(Complex &c2); Complex operator-(Complex &c2); Complex operator*(Complex &c2); Complex operator/(Complex &c2); void display(); private: double real; double imag; }; Complex Complex::operator +(Complex &c2) {Complex c; c.real=real+c2.real; c.imag=imag+c2.imag; return c; } Complex Complex::operator -(Complex &c2) {Complex c; c.real=real-c2.real; c.imag=imag-c2.imag; return c; } Complex Complex::operator *(Complex &c2) {Complex c; c.real=real*c2.real; c.imag=imag*c2.imag; return c; } Complex Complex::operator /(Complex &c2) {Complex c; c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); return c; } void Complex::display() {cout<<"("< } int main() {Complex c1(3,4),c2(5,-10),c3; 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; } 3. 有两个矩阵a 和b ,均为 n 行m 列(m 、n 的值自己给出) 求两个矩阵之和、差、积、商, 重载运算符“ + ”、” 使之能用于矩阵向 c=a*b 。 class Matrix 可第习窗呂童作业如5岭-Nexi Task8-3 /* */ #in elude viostream> #defi ne n 2 #defi ne m 3 using n amespace std; //定义Matrix 类 {public: Matrix(); //默认构造函数 frie nd Matrix operato 叶(Matrix &M atrix &); //重载运算符“ + ” friend Matrix operator-(Matrix &,Matrix &); friend Matrix operator*(Matrix &,Matrix &);