成员函数和友元函数 完成二元和一元运算符重载(进阶1)

本文通过实例展示了C++中复数类的二元和一元运算符重载技术,包括加法、减法及前缀/后缀递增/递减运算符的实现方法。介绍了作为成员函数和全局函数的重载方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二元运算符重载:

全局函数:

#include <iostream>
using namespace std;

class Complex{//复数类
private:
    int a;
    int b;
    friend Complex operator + (Complex &, Complex &);//注意声明友元函数
public:
    Complex(int a = 0, int b = 0){
        this->a = a;
        this->b = b;
    }
    void print(){
        cout << "a: " << a  << " " << "b: " << b << endl;
    }
};

Complex operator + (Complex &a1, Complex &a2){
    Complex tmp(a1.a + a2.a, a1.b + a2.b);
    return tmp;
}

int main()
{
    Complex c1(1, 2), c2(3, 4), c3;
    c3 = c1 + c2;
    c3.print();
    return 0;
}
类中:

#include <iostream>
using namespace std;

class Complex{//复数类
private:
    int a;
    int b;
public:
    Complex(int a = 0, int b = 0){
        this->a = a;
        this->b = b;
    }
    void print(){
        cout << "a: " << a  << " " << "b: " << b << endl;
    }
    Complex operator - (Complex &a2){
        Complex tmp(this->a - a2.a, this->b - a2.b);
        return tmp;
    }
};

int main()
{
    Complex c1(1, 2), c2(3, 4), c3;
    c3 = c1 - c2;
    c3.print();
    c3 = c2 - c1;
    c3.print();
    return 0;
}

一元运算符重载(难于二元)

类中和全局函数写在一块儿了

#include <iostream>
using namespace std;

class Complex{//复数类
private:
    int a;
    int b;
    friend Complex operator ++ (Complex &);
    friend Complex operator ++ (Complex &, int);
public:
    Complex(int a = 0, int b = 0){
        this->a = a;
        this->b = b;
    }
    void print(){
        cout << "a: " << a  << " " << "b: " << b << endl;
    }
    Complex operator -- (){ //前置--操作符,成员函数方法实现
        this->a --;
        this->b --;
        return (*this);
    }
    Complex operator --(int){ //后置--操作符,成员函数方法实现
        Complex tmp = (*this);
        this->a --;
        this->b --;
        return tmp;
    }
};

Complex operator ++ (Complex &A){ //前置++操作符,用全局函数实现
    A.a ++;
    A.b ++;
    return A;
}

Complex operator ++ (Complex &A, int){//后置++操作符,全局函数实现     加一个占位符跟前置加以区分
    Complex tmp = A;
    A.a ++;
    A.b ++;
    return tmp;
}

int main()
{
    Complex c1(1, 2);

    //前置++操作符,用全局函数实现
    ++c1;          //Complex c = operator ++ (c1);
    c1.print();

    //前置--操作符,成员函数方法实现
    --c1;          //Complex c = c1.operator -- (&c1)
    c1.print();

    //后置++操作符,全局函数实现
    c1++;          //Complex c = operator ++ (c1, 0);
    c1.print();
    
    //后置--操作符,成员函数方法实现
    c1--;          //Complex c = c1.operator -- (0);
    c1.print();

    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值