[c++]运算符重载

来源:互联网 发布:差距分析算法 编辑:程序博客网 时间:2024/04/29 08:51

类的声明:

#ifndef new_c___homework_operator_h#define new_c___homework_operator_h#include<iostream>using namespace std;class complex{public:    double real;    double imag;        complex(double r = 0,double i = 0)    {real = r; imag = i;}};complex operator+(complex co1,complex co2)//运算符重载函数{    complex temp;    temp.real = co1.real+co2.real;    temp.imag = co1.imag+co2.imag;    return temp;}//运算符重载函数写在类外,因为类中的两个成员被定义为公有    #endif



#include "operator.h"int main(){    complex com1(1.1,2.2);    complex com2(3.3,4.4);    complex total1;    complex total2;        total1 = operator+(com1,com2);//以该方式传值更能直观的表现出重载的作用    cout<<"real1 = "<<total1.real<<endl;    cout<<"imag1 = "<<total1.imag<<endl;    total2 = com1 + com2;    cout<<"real2 = "<<total2.real<<endl;    cout<<"imag2 = "<<total2.imag<<endl;    return 0;}


1.不能重载的运算符:

.    ::   *    ?:       #      sizeof

2.重载运算符可以对运算符做出新的解释,但原有基本语义不变:

不改变运算符原有优先级和结合性

单目重载单目,双目重载双目,不能混

不能创建新的运算符,只有系统预定义的运算符才能重载

经重载的运算符,其操作数中至少有一个是自定义类型

3.运算符通常是对类中私有成员进行操作,故重载运算符应能访问类中的私有成员,所以重载运算符一半采用成员函数友元函数的形式


下面是用成员函数实现:

#include<iostream>using namespace std;class complex{private:    double real;    double imag;public:    complex(double r = 0,double i = 0)    {real = r; imag = i;}    complex operator+(complex c);//运算符重载函数    complex operator-(complex c);    complex operator*(complex c);    complex operator/(complex c);    void print();};complex complex:: operator+(complex c){    complex temp;    temp.real = real+c.real;    temp.imag = imag+c.imag;    return temp;}complex complex:: operator-(complex c){    complex temp;    temp.real = real-c.real;    temp.imag = imag-c.imag;    return temp;}complex complex:: operator*(complex c){    complex temp;    temp.real = real*c.real-imag*c.imag;    temp.imag = real*c.imag+imag*c.real;    return temp;    }complex complex:: operator/(complex c){    complex temp;    double t;    t = real*c.real+imag*c.imag;    temp.real = (real*c.real-imag*c.imag)/t;    temp.imag = (real*c.imag+imag*c.real)/t;    return temp;    }void complex:: print(){    cout<<real;    if(imag > 0)    cout<<"+";    if(imag != 0)    cout<<imag<<"i"<<endl;}

main:

#include "operator.h"int main(){    complex com1(1.1,2.2);    complex com2(3.3,4.4);    complex A1;    complex A2;    complex A3;    complex A4;        A1 = com1 + com2;    A2 = com1 - com2;    A3 = com1 * com2;    A4 = com1 / com2;    A1.print();     A2.print();     A3.print();     A4.print();    return 0;}

单目运算符:

complex complex:: operator++(int)<span style="color: rgb(29, 148, 33); font-size: 18px; font-family: Menlo;">//(int)</span><span style="color: rgb(29, 148, 33); font-family: 'Heiti SC Light'; font-size: 18px;">只是一个为了与前缀自增的运算符重载函数有所区分因此可不必写参数名</span>{    real++;    imag++;    return *this;}complex complex:: operator++(){    ++real;    ++imag;    return *this;}


1 0
原创粉丝点击