重載運算符 operator=

類重載運算符,寫了兩個測試函數函數

第一種狀況,operator+測試

#include <stdio.h>

class Matrix {
friend Matrix operator+(const Matrix& a, const Matrix& b);
public:
        Matrix(const int a, const int b) {
                this->length = a;
                this->width = b;
        }
        ~Matrix() {

        }
        Matrix& operator+(const Matrix& a) {
                printf("class operator+ has been call\n");
                this->length += a.length;
                this->width += a.width;
                return *this;
        }
        void print() {
                printf("Matrix member length : %d, width : %d\n", length, width);
        }

private:
        int length;
        int width;
};

Matrix operator+(const Matrix& a, const Matrix& b){
        printf("global operator+ has been call\n");
        Matrix c(0, 0);
        c.length = a.length + b.length;
        c.width = a.width + b.width;
        return c;
}
int main() {
        Matrix a(1, 3);
        Matrix b(2, 4);
        Matrix c(0, 0);
        c = a + b;
        c.print();
        return 0;
}

代碼裏面一個是類Matrix的成員函數operator+,另外一個是外部函數operator+。兩個函數的做用域不同,成員函數的operator+屬於類域,然後者屬於全局域。this

因此在編譯器匹配函數調用時,先在類域找!類域找不到纔會到全局域找,因此此處調用的是成員函數。結果以下:spa

class operator+ has been call
Matrix member length : 3, width : 7

第二種狀況,operator=code

#include <stdio.h>

class Matrix {
public:
        Matrix(const int a, const int b) {
                this->length = a;
                this->width = b;
        }
        ~Matrix() {

        }
        Matrix& operator=(const Matrix& a){
                printf("class operator= has been call\n");
                this->length = a.length;
                this->width = a.width;
                return *this;
        }
        void print() {
                printf("Matrix member length : %d, width : %d\n", length, width);
        }

private:
        int length;
        int width;
};

Matrix& operator=(Matrix& a, const Matrix& b){
        printf("global operator= has been call\n");
        a.length = b.length;
        a.width = b.width;
        return a;
}
int main() {
        Matrix a(1, 3);
        Matrix b(2, 4);
        Matrix c(0, 0);
        c.print();
        return 0;
}

編譯報錯,提示信息:blog

tt.cpp:27: error: 'Matrix& operator=(Matrix&, const Matrix&)' must be a nonstatic member function

operator=必須由一個非靜態的成員函數來重載!什麼緣由不得其解?作用域

網上找了一些說法:編譯器

a、等於操做符存在一個左值的問題。函數返回值是一個臨時變量,而=操做符所做用的左值必須是一個有效地址。io

  按這個說法,能夠推測全部存在左值的操做符重載都必須定義爲非靜態成員函數。可是我測試了++運算符,很快發現這個說法不對編譯

b、僅僅是一個規定而已!任何語法規定都有其中緣由,關鍵是這個規定的出發點是什麼

求答疑解惑  

相關文章
相關標籤/搜索