• C++运算符重载小程序


    // chongzai.cpp : 定义控制台应用程序的入口点。
    //运算符重载+ -     友原函数的运用

    #include "stdafx.h"


    #include <iostream>
    using namespace std;
    class Complex
    {
    public:
     Complex( ) {real=0;
                 image=0;}
     Complex (double r,double i);

     Complex operator+ (Complex &c5);//重载加法声明(复数与复数相加) 对象
     friend Complex operator+ (double &,Complex &);//重载加法声明(整数与复数相加) 对象
        friend Complex operator+ (Complex &c5,double &a);//重载加法声明(复数与整数相加) 对象
     friend Complex operator- (Complex &c5,double &a);//重载加法声明(复数与整数相减) 对象
     friend Complex operator- (double &a,Complex &c5);//重载加法声明(整数与复数相减) 对象
     Complex operator- (Complex &c5);//重载减法声明 (复数与复数相减) 对象
     void display();//声明输出函数
     

    private:
     double  real;
     double  image;
    };

     Complex Complex::operator + (Complex &c5)//定义重载加法运算符 (复数与复数相加) 成员函数
    {
     
     return Complex(real+c5.real,image+c5.image);
    }
    Complex Complex::operator - (Complex &c5)//定义重载减法运算符  (复数与复数相减) 成员函数
    {
     Complex c;
     c.real=real-c5.real;
     c.image=image-c5.image;
     return c;
    }
     Complex operator+ (double &a,Complex &ca)//定义重载加法(整数与复数相加) 对象
    {
     
     return Complex(a+ca.real,ca.image);
    }
    Complex operator+ (Complex &c5,double &a)//定义重载加法(复数与整数相加) 对象
    {
     
     return Complex(c5.real+a,c5.image);
    }
    Complex operator- (Complex &c5,double &a)//定义重载加法(复数与整数相减) 对象
    {
     return Complex(c5.real-a,c5.image);
    }

    Complex operator- (double &a,Complex &c5)//定义重载加法(复数与整数相减) 对象
    {
     
     return Complex(a-c5.real,c5.image);
    }

    Complex::Complex(double r,double i)//重载构造函数
    {
                 real=r;
                 image=i;
    }

    void Complex::display ()
    {
     cout <<"("<<real<<","<<image<<")"<<endl;
    }
    int main ()
    {
    Complex c1(3,2),c2(1,2),c3,c4,c7,c8;
    double m=2;
    c3=c1+c2;

    c3.display();
    c4=c3-c1;
    c4.display();
    c7=m+c1;
    c7.display();
    c8=m-c3;
    c8.display();
    return 0;
    }

  • 相关阅读:
    JAVA开发人员画图表总结(ECHARTS)
    Spring Validation 表单校验
    Java BIO、NIO、AIO 学习
    JAVA笔试题
    JAVA GC优化入门
    jstat 使用日志
    JAVA内存泄漏
    JAVA 线程池入门事例
    JAVA Semaphore
    Serializable 介绍
  • 原文地址:https://www.cnblogs.com/lixingle/p/3313064.html
Copyright © 2020-2023  润新知