10. C++操作符重載

在介紹C++中操作符重載之前,先介紹下C++標準庫。

一、C++標準庫

         1. C++標準庫並不是C++語言的一部分;
                2. C++標準庫是由C++語言編寫而成的類庫和函數的集合;
                3. C++標準庫中定義的類和對象都位於std命名空間中;
                4. C++標準庫的頭文件都不帶.h後綴;
                5. C++標準庫涵蓋了C庫的功能;
                           C庫中<name.h>頭文件對應C++中的<cname>;

C++標準庫預定義了多數常用的數據結構,如:字符串,鏈表,隊列,棧等。<bitset>  <deque>  <list>  <map>  <queue>  <set>  <stack>  <vector>

#include <cstdio>

using namespace std;

int main()
{
	printf("Hello World!\n");

	printf("Press any key to continue...");

	getchar();

	return 0;
}

#include <iostream>

using namespace std;

int main()
{
	cout<<"Hello World"<<endl;
    
	int x;
	int y;

	cout<<"1st Parameter: ";
	cin>>x;

	cout<<"2nd Parameter: ";
	cin>>y;

	cout<<"Result: "<<x+y<<endl;

	return 0;
}

左移運算符 << 和 右移運算符 >> 在C語言中只能用於整數運算,並且語義是確定不變的。C++是怎麼改變左移運算符和右移運算符的語義的?

 

二、操作符重載

操作符重載爲操作符提供不同的語義。

#include <cstdlib>
#include <iostream>

using namespace std;

struct Complex
{
    int a;
    int b;
};

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

編譯運行結果如下:

很顯然,編譯出錯了,不管是C還是C++中,“+”符號只能用於整數和浮點數的相加。這裏是兩個結構體相加,那肯定要報錯了。那該怎麼解決這個問題呢?

可以定義一個add函數用於兩個Complex的相加。

#include <cstdlib>
#include <iostream>

using namespace std;

struct Complex
{
    int a;
    int b;
};

Complex add(const Complex& c1, const Complex& c2)
{
    Complex ret;
    
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    
    return ret;
}

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

編譯運行結果如下:

add函數可以解決Complex變量相加的問題,但是Complex是現實世界中確實存在的複數,並且複數在數學中的地位和普通的實數相同。爲什麼不能讓 + 操作符也支持複數相加呢?

 

C++中操作符重載的本質
               1. C++中通過operator關鍵字可以利用函數擴展操作符;
               2. operator的本質是通過函數重載實現操作符重載;

#include <cstdlib>
#include <iostream>

using namespace std;

struct Complex
{
    int a;
    int b;
};

Complex operator+(const Complex& c1, const Complex& c2)
{
    Complex ret;
    
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    
    return ret;
}

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

編譯運行結果如下:

用operator關鍵字擴展的操作符可以用於類嗎?

#include <cstdlib>
#include <iostream>

using namespace std;

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& c1, const Complex& c2)
{
    Complex ret;
    
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    
    return ret;
}

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

編譯運行結果如下:

該怎麼進行改進呢?

C++中的類的友元

        private聲明使得類的成員不能被外界訪問。但是通過friend關鍵字可以例外的開放權限。

 

#include <cstdlib>
#include <iostream>

using namespace std;

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& c1, const Complex& c2);
};

Complex operator+ (const Complex& c1, const Complex& c2)
{
    Complex ret;
    
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    
    return ret;
}

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

 編譯運行結果如下:

 

左移操作符的重載 

#include <cstdlib>
#include <iostream>

using namespace std;

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& c1, const Complex& c2);
    friend ostream& operator<< (ostream& out, const Complex& c);
};

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

Complex operator+ (const Complex& c1, const Complex& c2)
{
    Complex ret;
    
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    
    return ret;
}

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

編譯結果如下:

關於ostream的詳細用法可以參考https://blog.csdn.net/luoyayun361/article/details/87972929

小結:

        1. 操作符重載是C++的強大特性之一
                2. 操作符重載的本質是通過函數擴展操作符的語義
                3. operator關鍵字是操作符重載的關鍵
                4. friend關鍵字可以對函數或類開發訪問權限
                5. 操作符重載遵循函數重載的規則

 

 

通過operator關鍵字能夠將操作符定義爲全局函數。操作符重載的本質就是函數重載。類的成員函數是否可以作爲操作符重載的函數?

operator+的成員函數實現

用成員函數重載的操作符,比全局操作符重載函數少一個參數,即左操作數。不需要使用friend關鍵字。

#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);
    
    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+ (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 = c1 + c2;
    
    cout<<c1<<endl;
    cout<<c2<<endl;
    cout<<c3<<endl;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

編譯運行結果如下:

什麼時候使用全局函數重載操作符?什麼時候使用成員函數重載操作符?

當無法修改左操作數的類時,使用全局函數進行重載。=, [], ()和->操作符只能通過成員函數進行重載。
 

數組類的改進

       重載賦值操作符,重載數組操作符,重載比較操作符

//Array.cpp
#include <stdio.h>
#include "Array.h"

Array::Array(int length)
{
    if( length < 0 )
    {
        length = 0;
    }
    
    mLength = length;
    mSpace = new int[mLength];
}

Array::Array(const Array& obj)
{
    mLength = obj.mLength;
    
    mSpace = new int[mLength];
    
    for(int i=0; i<mLength; i++)
    {
        mSpace[i] = obj.mSpace[i];
    }
}

int Array::length()
{
    return mLength;
}

Array::~Array()
{
    mLength = -1;
    printf("%08X\n", mSpace);
    delete[] mSpace;
}

int& Array::operator[](int i)
{
    return mSpace[i];
}

Array& Array::operator= (const Array& obj)
{
    delete[] mSpace;
    
    mLength = obj.mLength;
    
    mSpace = new int[mLength];
    
    for(int i=0; i<mLength; i++)
    {
        mSpace[i] = obj.mSpace[i];
    }
    
    return *this;
}

bool Array::operator== (const Array& obj)
{
    bool ret = true;
    
    if( mLength == obj.mLength )
    {
        for(int i=0; i<mLength; i++)
        {
            if( mSpace[i] != obj.mSpace[i] )
            {
                ret = false;
                break;
            }
        }
    }
    else
    {
        ret = false;
    }
    
    return ret;
}

bool Array::operator!= (const Array& obj)
{
    return !(*this == obj);
}
//Array.h
#ifndef _ARRAY_H_
#define _ARRAY_H_

class Array
{
private:
    int mLength;
    int* mSpace;

public:
    Array(int length);
    Array(const Array& obj);
    int length();
    ~Array();
    int& operator[](int i);
    Array& operator= (const Array& obj);
    bool operator== (const Array& obj);
    bool operator!= (const Array& obj);
};

#endif
//main.cpp
#include <stdio.h>
#include "Array.h"

int main()
{
    Array a1(10);
    Array a2(0);
    Array a3(0);
    
    if( a1 != a2 )
    {
        printf("a1 != a2\n");
    }
    
    for(int i=0; i<a1.length(); i++)
    {
        a1[i] = i + 1;
    }
    
    for(int i=0; i<a1.length(); i++)
    {
        printf("Element %d: %d\n", i, a1[i]);
    }
    
    a3 = a2 = a1;
    
    if( a1 == a2 )
    {
        printf("a1 == a2\n");
    }
    
    for(int i=0; i<a2.length(); i++)
    {
        printf("Element %d: %d\n", i, a2[i]);
    }
    
    printf("Press any key to continue...");
    getchar();
    return 0;
}

編譯運行結果如下:

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;
}

編譯運行結果如下:

 

不要重載&&和||操作符,爲什麼?

#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;
}

編譯運行結果如下:

&&和||是C++中非常特殊的操作符。&&和||內置實現了短路規則,操作符重載是靠函數重載來完成的,操作數作爲函數參數傳遞,C++的函數參數都會被求值,無法實現短路規則。
 

小結

       1. 操作符重載可以直接使用類的成員函數實現;

       2. =, [], ()和->操作符只能通過成員函數進行重載;

       3. ++操作符通過一個int參數進行前置與後置的重載;

       4. C++中不要重載&&和||操作符;
 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章