操作符的重载c++

通过operator关键字能够将操作符定义为全局函数

操作符重载的本质就是函数重载

operator+的成员 函数实现

用成员函数重载的操作符 比全局操作符重载函数少一个参数,即左操作数 不需要使用friend关键字

<=>

~什么时候使用全局函数重载操作符?

当无法修改左操作数的类时,使用全局函数进行重载

~什么时候使用成员函数重载操作符?

=, [], ()和->操作符只能通过成员函数进行重载

C++编译器会为每个类提供默认的赋值操作符 ,默认的赋值操作符只是做简单的值复制, 类中存在指针成员变量时就需要重载赋值操作符

//////////////////////////////////////////////////////////////////////////////////////////////////////

++操作符的重载 ++操作符只有一个操作数 ++操作符有前缀和有后缀的区分

C++中通过一个占位参数来区分前置运算和后置运算

#include <cstdlib>
#include <iostream>

using namespace std;

class Complex
{
    int a;
    int b;
public:
    Complex(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    
    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }
    
    Complex operator+ (const Complex& c2);
    Complex operator++ (int);
    Complex& operator++();
    
    friend ostream& operator<< (ostream& out, const Complex& c);
};

ostream& operator<< (ostream& out, const Complex& c)
{
    out<<c.a<<" + "<<c.b<<"i";
    
    return out;
}

Complex Complex::operator++ (int)
{
    Complex ret = *this;
    
    a++;
    b++;
    
    return ret;
    
}

Complex& Complex::operator++()
{
    ++a;
    ++b;
    
    return *this;
}

Complex Complex::operator+ (const Complex& c2)
{
    Complex ret(0, 0);
    
    ret.a = this->a + c2.a;
    ret.b = this->b + c2.b;
    
    return ret;
}

int main(int argc, char *argv[])
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c2;
    
    c2++;
    ++c3;
    
    cout<<c1<<endl;
    cout<<c2<<endl;
    cout<<c3<<endl;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////

~不要重载&&和||操作符

&&和||是C++中非常特殊的操作符 &&和||内置实现了短路规则 操作符重载是靠函数重载来完成的 操作数作为函数参数传递 C++的函数参数都会被求值,无法实现短路规则

example:

#include <cstdlib>
#include <iostream>

using namespace std;

class Test
{
    int i;
public:
    Test(int i)
    {
        this->i = i;
    }
    
    Test operator+ (const Test& obj)
    {
        Test ret(0);
        
        cout<<"Test operator+ (const Test& obj)"<<endl;
        
        ret.i = i + obj.i;
        
        return ret;
    }
    
    bool operator&& (const Test& obj)
    {
        cout<<"bool operator&& (const Test& obj)"<<endl;
        
        return i && obj.i;
    }
};

int main(int argc, char *argv[])
{
    int a1 = 0;
    int a2 = 1;
    
    if( a1 && (a1 + a2) )
    {
        cout<<"Hello"<<endl;
    }
    
    Test t1 = 0;
    Test t2 = 1;
    
    if( t1 && (t1 + t2) )
    {
        cout<<"World"<<endl;
    }
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}
 

猜你喜欢

转载自blog.csdn.net/qq_41660466/article/details/81076749
今日推荐