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

二元运算符重载:

全局函数:

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






阅读更多
版权声明:本文为博主原创文章,如能转载,不胜荣幸。 https://blog.csdn.net/x_y_q_/article/details/52201193
个人分类: C++学习心路
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭