重载运算符 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+属于类域,而后者属于全局域。

所以在编译器匹配函数调用时,先在类域找!类域找不到才会到全局域找,所以此处调用的是成员函数。结果如下:

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

第二种情况,operator=

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

编译报错,提示信息:

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

operator=必须由一个非静态的成员函数来重载!什么原因不得其解?

网上找了一些说法:

a、等于操作符存在一个左值的问题。函数返回值是一个临时变量,而=操作符所作用的左值必须是一个有效地址。

  按这个说法,可以推测所有存在左值的操作符重载都必须定义为非静态成员函数。但是我测试了++运算符,很快发现这个说法不对

b、仅仅是一个规定而已!任何语法规定都有其中原因,关键是这个规定的出发点是什么

求答疑解惑  

 

posted @ 2016-05-13 10:45  一介莽夫  阅读(486)  评论(0编辑  收藏  举报