重载运算符 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、仅仅是一个规定而已!任何语法规定都有其中原因,关键是这个规定的出发点是什么

求答疑解惑  

 

转载于:https://www.cnblogs.com/job-views/p/5488562.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值