zoukankan      html  css  js  c++  java
  • C++ 运算符重载

    1、运算符重载

    • 对已有的运算符赋予多重的含义
    • 使同一运算符作用于不同类型的数据时产生不同类型的行为

    目的

    • 扩展C++中提供的运算符的适用范围,以用于类所表示的抽象数据类型

    运算符的重载实质是函数重载,类型如下:

    返回值类型 operator 运算符(形参表)
    {
        ...    
    }

    在程序编译时

    • 把含运算符的表达式 -> 对 运算符函数  的调用
    • 把运算符的操作数作为运算符函数的参数
    • 运算符被多次重载时,根据实参的类型决定调用哪个运算符函数
    • 运算符可以被重载成普通函数,也可以被重载成类的成员函数

    运算符重载为普通函数示例:

    #include <iostream>
    
    using namespace std;
    
    class Complex {
    public:
        Complex(double r = 0.0, double i = 0.0) {
            real = r;
            img = i;
        }
    
        double real; // real part
        double img; // imaginary part
    };
    
    Complex operator + (const Complex &a, const Complex &b)
    {
        return Complex(a.real+b.real, a.img+b.img);
    }
    
    int main()
    {
        Complex a(1, 2), b(2, 3), c;
        c = a + b;
        cout << c.real << ":" << c.img << endl;
    }

    这里a+b 就相当于 operator+(a, b);

    重载为普通函数时,参数个数为运算符数目。

    运算符重载为成员函数示例:(重载为成员函数时,参数个数为运算符数目减一)

    #include <iostream>
    
    using namespace std;
    
    class Complex {
    public:
        Complex(double r = 0.0, double i = 0.0) {
            real = r;
            img = i;
        }
        Complex operator+(const Complex &); // addition
        Complex operator-(const Complex &); // subtraction
    
    
        double real; // real part
        double img; // imaginary part
    };
    
    Complex Complex::operator +(const Complex & operand2)
    {
        return Complex(real+operand2.real, img+operand2.img);
    }
    
    Complex Complex::operator -(const Complex & operand2)
    {
        return Complex(real-operand2.real, img-operand2.img);
    }
    
    int main()
    {
        Complex a(1, 2), b(2, 3), c;
        c = a + b;
        cout << c.real << ":" << c.img << endl;
        c = b - a;
        cout << c.real << ":" << c.img << endl;
    }
  • 相关阅读:
    System.IO命名空间
    Java调用Http/Https接口(8,end)OkHttp调用Http/Https接口
    javascript上传组件
    在ubuntu下安装MonoDevelop
    Sql Server中Null+nvarchar结果为null
    利用iframe实现javascript无刷新载入整页
    C#序列化和反序列化
    vmware7.0下搭建ubuntuNat上网/C++开发环境
    javascript模态窗口Demo
    为博客添加在线台湾卫星电视播放功能
  • 原文地址:https://www.cnblogs.com/aqing1987/p/4331136.html
Copyright © 2011-2022 走看看