• 第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;
    }
  • 相关阅读:
    主流液晶显示器尺寸参数
    不能访问网络位置的解决方法(转)
    打开Word提示你正试图运行的函数包含有宏或需要宏语言支持的内容
    教你如何防“蹭网”
    ASA数据库瘦身(原创)
    多种解决:“Word无法启动转换器mswrd632.wpc”方法
    百兆线与千兆线网线制作方法
    linux常用命令
    DefaultIfEmpty
    实现手机发送验证码 进行验证
  • 原文地址:https://www.cnblogs.com/huangdengtao/p/11866965.html
Copyright © 2020-2023  润新知