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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM