百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> Js中加法运算重载的用法
分享文章到:

Js中加法运算重载的用法

发布时间:01/15 来源: 浏览: 关键词:
下文我们一起来看一篇关于Js中加法运算重载的用法了这包括了基本的知识与之后的运算符重载返回新的对象的例子,具体如下所示。

加法运算重载

调用对象自身成员变量发送改变 标签: <无>
代码片段

#pragma once
class Complex
{
public:
    Complex(void);
    ~Complex(void);
    Complex(int real,int imag);
    int get_real()const;
    int get_imag()const;
    void Display()const;

    void Addone(const Complex& other);
    Complex operator+(const Complex& other);

private:
    int real_;
    int imag_;
};
Complex::Complex(void) {}
Complex:: Complex(int real,int imag):real_(real),imag_(imag) {}

int Complex:: get_real()const
{   return real_;
}

int Complex:: get_imag ()const
{   return imag_;
}

void Complex::Display()const
{   cout<<real_<<','<<imag_<<endl;
};

void Complex::Addone(const Complex& other)
{   real_+=other.get_real();
    imag_+=other.get_imag();

}
Complex Complex::operator+(const Complex& other)//调用对象自身的值发生了改变
{   real_+=other.get_real();
    imag_+=other.get_imag();
    return *this;
}


Complex::~Complex(void)
{
}
#include<iostream>
#include "Complex.h"
using namespace std;

Complex Add( Complex& A, Complex& B)
{   return Complex(A.get_real()+B.get_real(),A.get_imag()+B.get_imag());
};

void main()
{   Complex a(10,5);
    Complex b(11,0);
    Complex c;

    a.Display();
    b.Display();

    c = Add(a,b);
    c.Display();

    c.Addone(a);
    c.Display();

    a+b; //与a的类成员函数调用a.operator+(b)等价
 a.Display();
}

运算符重载返回新的对象


代码片段

#pragma once
class Complex
{
public:
    Complex(void);
    ~Complex(void);
    Complex(int real,int imag);
    int get_real()const;
    int get_imag()const;
    void Display()const;

    void Addone(const Complex& other);
    Complex operator+(const Complex& other);

private:
    int real_;
    int imag_;
};
#include "Complex.h"

#include<iostream>
using namespace std;

Complex::Complex(void) {}
Complex:: Complex(int real,int imag):real_(real),imag_(imag) {}

int Complex:: get_real()const
{   return real_;
}

int Complex:: get_imag ()const
{   return imag_;
}

void Complex::Display()const
{   cout<<real_<<','<<imag_<<endl;
};

void Complex::Addone(const Complex& other)
{   real_+=other.get_real();
    imag_+=other.get_imag();

}
//Complex Complex::operator+(const Complex& other)//调用对象自身的值发生了改变
//{   real_+=other.get_real();
//    imag_+=other.get_imag();
//    return *this;
/

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有4人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板