C++中的操作符重载

2017-10-14  本文已影响0人  nethanhan

操作符重载


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

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

这里举一个例子:

#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;
    }
    
    //声明操作符重载
    friend Complex operator + (const Complex& p1, const Complex& p2);
};

//定义操作符重载
Complex operator + (const Complex& p1, const Complex& p2)
{
    Complex ret;
    
    //因为是友元,所以可以直接访问成员变量
    ret.a = p1.a + p2.a;
    ret.b = p1.b + p2.b;
    
    return ret;
}

int main()
{

    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2; // operator + (c1, c2)
    
    printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
    
    return 0;
}

另一种用法:

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

这里再举一个例子:

#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)\n");
        ret.a = this->a + p.a;
        ret.b = this->b + p.b;
        
        return ret;
    }
    
    friend Complex operator + (const Complex& p1, const Complex& p2);
};

Complex operator + (const Complex& p1, const Complex& p2)
{
    Complex ret;
    printf("Complex operator + (const Complex& p1, const Complex& p2)\n");
    ret.a = p1.a + p2.a;
    ret.b = p1.b + p2.b;
    
    return ret;
}

int main()
{

    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2; // c1.operator + (c2)
    
    printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
    
    return 0;
}

小结


上一篇 下一篇

猜你喜欢

热点阅读