C++基础——运算符重载

1 概述

程序员可以对C++中的+、=等运算符重新定义,以适应不同数据类型的计算。
运算符重载规则:

  • 重载后的运算符不能改变原有运算符的运算规则(加号运算符不能重载为两个数相减)
  • 不能定义原本没有的运算符
    运算符重载语法:
retValue operator[+-*/...](param1, param2) {
   }

使用operator关键字,后接要重载的运算符,其他的都是和普通函数定义相同。

2 常用运算符重载

2.1 加号运算符重载

#include <iostream>
using namespace std;

class TestClass {
   
public:
    TestClass(){
   };
    TestClass(int a, int b):mA(a),mB(b){
   };

    TestClass operator+(const TestClass& TestClass) const {
   
        class TestClass temp;
        temp.mA = this->mA + TestClass.mA;
        temp.mB = this->mB + TestClass.mB;
        return temp;
    }
public:
    int mA;
    int mB;
};

// TestClass operator+(const TestClass& testClass1, const TestClass& testClass2) {
   
//     class TestClass temp;
//     temp.mA = testClass1.mA + testClass2.mA;
//     temp.mB = testClass1.mB + testClass2.mB;
//     return temp;
// }

int main() {
   
    TestClass testClass1(10,20);
    TestClass testClass2(30,40);
    TestClass testClass3 = testClass1 + testClass2;
    cout << "testClass3.mA = " << testClass3.mA << endl;
    cout << "testClass3.mB = " << testClass3.mB << endl;
    return 0;
}

加法运算符重载,可以实现两个对象相加返回一个对象,而对象的哪些属性参与运算则由软件开发者自己定义。
可以通过全局函数实现,也可以通过成员函数实现。二者的区别是全局函数需要传入两个参数,而成员函数由于this指针的存在只需要传入一个参数。
需要注意的是这里的全局函数实现和成员函数实现不能同时存在,因为调用的时候会产生分歧,不知道应该调用成员函数还是全局函数。

2.2 左移运算符重载

通常输入输出操作都是通过流来实现,像cout、cin函数,就是重载了左移和右移运算符的,通常重写这两个运算符也是为了文件的输入输出操作。

#include <iostream>

using namespace std;

class TestClass {
   
    friend ostream& operator<<(ostream& out, TestClass& testClass);
public:
    TestClass() {
   };

    TestClass(int a, int b) : mA(a), mB(b) {
   };

    void operator<<(ostream &out) const {
   
        out 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值