C++重载函数运算符的两种定义方法(类中|类外(友元))、重载操作运算符

一、C++中重载运算符函数的方式:

以重载‘-’号为例,自定义为乘法。

第一种是直接在类内声明定义:(返回值是本类的对象)

#include <iostream>
using namespace std;
class test
{
public:
    test() {}
    test(int t1)
    {
        item = t1;
    }
    test operator-(test &t2)
    {
        this->item = this->item*t2.item;
        return *this;
    }
    void show()
    {
        cout << this->item;
    }

private:
    int item;
};
int main()
{
    test t1(10);
    test t2(20);
    test t3 = t1 - t2;
    t3.show();
    system("pause");
    return 0;
}

第二种是在类中声明为友元函数,类外定义,返回值的是一个类的对象。(一般为了能在类外直接调用成员而不用通过成员函数间接调用成员数据)

#include <iostream>
using namespace std;
class test
{
public:
    test() {}
    test(int t1)
    {
        item = t1;
    }
    void show()
    {
        cout << this->item;
    }
    friend test operator-(test &t1, test &t2);         
private:
    int item;
};
test operator-(test &t1, test &t2)
{
    test t;
    t.item = t1.item*t2.item;
    return t;
}
int main()
{
    test t1(10);
    test t2(20);
    test t3 = t1 - t2;
    t3.show();
    system("pause");
    return 0;
}


/*注意,如果新建立一个对象test t4(30);
test t3=t1-t2-t4;
此时运算符重载函数依然可以使用,但是,如果将运算符重载函数声明定义为返回的是一个对象的引用,t1-t2这一步骤完成后,做-t4这一步骤,此时会出现乱码,
因为运算符重载函数返回的是一个对象的引用时,产生临时变量temp,但是会消失,此时对temp进行引用时已经不存在这个值了,所以出现乱码
*/

二、C++中操作符重载函数

操作符重载函数中的重载左移操作符,其函数定义不建议写在类中,因为cout<<test,左边是ofstream对象,如果放到类中定义,其调用是test.operator<<,

变成test<<cout

右移操作符大同小异

#include <iostream>
using namespace std;

class test 
{
public:
    test(){}
    test(int t){
        temp=t;
    }
    void show()
    {
        cout<<temp;
    }
    friend ostream& operator<<(ostream &os,test &t1);     //为了能直接调用类的数据成员,声明为友元函数
private:
    int temp;
};
ostream& operator<<(ostream &os,test &t1)                  //<<操作符重载函数只写在全局,
{
    os<<t1.temp<<endl;
    return os;
}

int main()
{
    test t1(10);
    cout<<t1;
    system("pause");
    return 0;
}

注!操作符重载函数返回引用目的是为了能够连续赋值。如:cout<<a<<b<<c<<endl;

原文地址:https://www.cnblogs.com/god-for-speed/p/10941044.html