zoukankan      html  css  js  c++  java
  • 第30课.操作符重载的概念

    问题:+ 操作符不能支持复数相加
    解决方案:c++中的重载能够扩展操作符的功能

    1.操作符重载

    a.通过operator关键字可以定义特殊的函数
    b.operator的本质是通过函数重载操作符
    语法:

    Type operator Sign(const Type p1, const Type p2)
    {
        Type ret;
        
        return ret;
    }
    

    Sign为系统中预定义的操作符,如+, -, *, /,等等

    ===
    a.可以将操作符重载函数定义为类的成员函数
    b.定义为类的成员函数比全局操作符重载函数少一个参数(左操作数,因为可以直接使用this指针。即只需要右操作数)
    c.不依赖友元就可以完成函数重载。
    d.编译器优先在成员函数中寻找操作符的重载函数(同时定义了全局重载函数时,优先调用成员函数,成员函数被调用后,就不会去调用全局函数了。)
    eg:

    class Type
    {
    public:
        Type operator Sign(const Type& p)
        {
            Type ret;
    
            return ret;
         }
    };
    

    eg:复数加法

    #include <stdio.h>
    
    class Complex
    {
        int a;
        int b;
        
    public:
        Complex(int a = 0, int b = 0)
        {
            this->a = a;
            this->b = b;
        }
        
        int getA()
        {
            return a;
        }
    
        int getB()
        {
            return b;
        }
        
        Complex operator + (const Complex& p)        //重载
        {
            Complex ret;
            printf("Complex operator + (const Complex& p)
    ");
            ret.a = this->a + p.a;
            ret.b = this->b + p.b;
            
            return ret;
        }
        
       // friend Complex operator + (const Complex p1, const Complex p2);
    };
    
    #if 0
    Complex operator + (const Complex p1, const Complex p2)
    {
        Complex ret;
        printf("Complex operator + (const Complex& p1, const Complex& p2)
    ");
        ret.a = p1.a + p2.a;
        ret.b = p1.b + p2.b;
            
        return ret;
    }
    
    /*  两个函数同时使用时:
        1.cpp:52: error: ambiguous overload for ‘operator+’ in ‘c1 + c2’
        1.cpp:25: note: candidates are: Complex Complex::operator+(const Complex&)
        1.cpp:38: note:                 Complex operator+(Complex, Complex)
     */
    
    #endif
    
    int main()
    {
        Complex c1(1, 2);
        Complex c2(3, 4);
        Complex c3 = c1 + c2; // c1.operator + (c2)
        
        printf("c3.a = %d, c3.b = %d
    ", c3.getA(), c3.getB());
        
        return 0;
    }
  • 相关阅读:
    vue指令(3)v-html
    vue指令(2)v-text
    vue基础(2)模板语法
    Struts2中在Action里面向前端页面传值的方法总结
    MySQL之字符串函数
    搜索关键字描红
    点击超链接执行js代码实现确认操作
    Java之线程同步的三种方法
    Java之线程的控制
    Java之线程的生命周期
  • 原文地址:https://www.cnblogs.com/huangdengtao/p/11866965.html
Copyright © 2011-2022 走看看