关闭

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

350人阅读 评论(0) 收藏 举报
分类:

二元运算符重载:

全局函数:

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






1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32481次
    • 积分:1393
    • 等级:
    • 排名:千里之外
    • 原创:111篇
    • 转载:14篇
    • 译文:0篇
    • 评论:5条
    最新评论