【C++封装】重载运算符

文章介绍了C++中如何重载常见的运算符,如输出、加法、相等、加加减减运算符,以及函数调用运算符的使用。同时,讲解了全局函数和成员函数两种方式来实现运算符重载,并展示了智能指针的概念,如何通过类包装指针并自动管理内存。
摘要由CSDN通过智能技术生成

文章内容如下:

1)重载输出运算符

2)重载加法运算符

3)重载相等运算符

4)重载加加减减运算符

5)重载函数调用运算符

6)智能指针

        重载运算符就是对已有的运算符进行重定义,赋予另一种功能,目的是为了适应不同的数据类型。定义重载运算符就想定义函数,只是该函数的名字是operator@,这里的@代表被重载的运算符。一般重载运算符思路如下:

1. 弄懂运算符的运算对象个数,因为个数决定了重载函数的参数个数;

2. 识别运算符左边的运算对象是类的对象还是其他。类的对象可以用 全局函数实现(不推荐),成员函数实现(推荐,少一个参数),其他的则只能用全局函数实现。

一。全局函数重载输出运算符

#include <iostream>
using namespace std;
#include <string>

class Person
{
    friend ostream& operator<<(ostream& out,Person& ob );
private:
    int num;
    string name;
    float score;
public:
    Person(){}
    Person(int num,string name,float score):num(num),name(name),score(score){}
};

"""全局函数重载声明了有元,有元一般不考虑是成员函数,仍然认为这里是全局函数"""
ostream&  operator<<(ostream& out,Person& ob )
{
    out << ob.num << " " << ob.name << " " << ob.score << endl;
    return out;
}

int main()
{

    Person lucy(100,"lucy",99.8f);
    cout<<lucy<<endl;
    return 0;
}

 附:全局函数重载输入运算符

#include <iostream>
using namespace std;
#include <string>

class Person
{
    ostream&  operator<<(ostream& out,Person ob );
    friend istream&   operator>>(istream& in,Person& ob );
private:
    int num;
    string name;
    float score;
public:
    Person(){}
    Person(int num,string name,float score):num(num),name(name),score(score){}
};

"""全局函数重载声明了有元,有元一般不考虑是成员函数,仍然认为这里是全局函数"""
istream&  operator>>(istream& in,Person& ob )
{
    in >> ob.num >>  ob.name >> ob.score;
    return in;
}

ostream&  operator<<(ostream& out,Person& ob )
{
    out << ob.num << " " << ob.name << " " << ob.score << endl;
    return out;
}

int main()
{

    Person lucy;
    Person bob;
    cin>>lucy;
    cout<<lucy<<bob<<endl;
    return 0;
}

 二。重载加法运算符

1.全局函数重载加法运算符

#include <iostream>
using namespace std;
#include <string>

class Person
{
    ostream&  operator<<(ostream& out,Person ob );
    friend istream  operator+(Person& ob1,Person ob2 );
private:
    int num;
    string name;
    float score;
public:
    Person(){}
    Person(int num,string name,float score):num(num),name(name),score(score){}
};

"""全局函数重载声明了有元,有元一般不考虑是成员函数,仍然认为这里是全局函数"""
istream  operator+(Person& ob1,Person& ob2 )
{
    Person tmp;
    tmp.num = ob1.num+ob2.num;
    tmp.name=ob1.name+ob2.name;
    tmp.score=ob1.score+ob2.score;
    return tmp;
}

ostream&  operator<<(ostream& out,Person ob )
{
    out << ob.num << " " << ob.name << " " << ob.score << endl;
    return out;
}

int main()
{

    Person lucy(100,"lucy",88.8);
    Person bob(101,"bob",99.9);
    cout<<lucy+bob<<endl;
    return 0;
}

2.成员函数重载加法运算符

#include <iostream>
using namespace std;
#include <string>

class Person
{
    friend ostream&  operator<<(ostream& out,Person ob );
private:
    int num;
    string name;
    float score;
public:
    Person(){}
    Person(int num,string name,float score):num(num),name(name),score(score){}
    """成员函数重载加法运算符"""
    istream  operator+(Person& ob2 )
        {
            Person tmp;
            tmp.num = num+ob2.num;
            tmp.name=name+ob2.name;
            tmp.score=score+ob2.score;
            return tmp;
        }
};

ostream&  operator<<(ostream& out,Person ob )
{
    out << ob.num << " " << ob.name << " " << ob.score << endl;
    return out;
}

int main()
{

    Person lucy(100,"lucy",88.8);
    Person bob(101,"bob",99.9);
    cout<<lucy+bob<<endl;"""等价于cout<<lucy.operator+(bob)<<endl"""
    return 0;
}

三。重载相等运算符

#include <iostream>
using namespace std;
#include <string>

class Person
{
private:
    int num;
    string name;
    float score;
public:
    Person(){}
    Person(int num,string name,float score):num(num),name(name),score(score){}
    """成员函数重载相等运算符"""
    bool operator==(Person& ob)
        {
            if(num==ob.num && name==ob.name && score==ob.score)
                {
                    return true;
                }
            else
                {
                    return false;
                }
        }
};

int main()
{

    Person lucy(100,"lucy",88.8);
    Person bob(101,"bob",99.9);
    if (lucy == bob)
        {
            cout << "相等" << endl;
        }
    else
        {
            cout << "不相等" << endl;
        }
    return 0;
}

四。重载加加减减运算符

        重载的++和--运算符有点让人不知所措,因为我们总是希望能根据他们出现在所作用对象的前面还是后面来调研不同的函数。解决办法很简单,加占位参数。例如当编译器看到++a时它就调用operator++(a),当编译器看到a++时它就调用operator++(a,int)。

1.后置++

  

#include <iostream>
using namespace std;
#include <string>

class Person
{
    friend ostream&  operator<<(ostream& out,Person ob );
private:
    int num;
    string name;
    float score;
public:
    Person(){}
    Person(int num,string name,float score):num(num),name(name),score(score){}
    Person operator++(int)
    {
        Person old = *this;
        this->num++;
        this->name = this->name+this->name;
        this->score;
        return old;
    }
};

ostream&  operator<<(ostream& out,Person ob )
{
    out << ob.num << " " << ob.name << " " << ob.score << endl;
    return out;
}

int main()
{
    Person lucy(100,"lucy",88.8);
    Person bob;
    bob = lucy++;
    cout<<bob<<endl;
    cout<<lucy<<endl;
    return 0;
}

2.前置++

#include <iostream>
using namespace std;
#include <string>

class Person
{
    friend ostream&  operator<<(ostream& out,Person ob );
private:
    int num;
    string name;
    float score;
public:
    Person(){}
    Person(int num,string name,float score):num(num),name(name),score(score){}
    Person operator++()
    {
        this->num++;
        this->name = this->name+this->name;
        this->score;
        return *this;
    }
};

ostream&  operator<<(ostream& out,Person ob )
{
    out << ob.num << " " << ob.name << " " << ob.score << endl;
    return out;
}

int main()
{
    Person lucy(100,"lucy",88.8);
    Person bob;
    bob = ++lucy;
    cout<<bob<<endl;
    cout<<lucy<<endl;
    return 0;
}

五。重载函数调用运算符

        函数调用运算符就是指小括号()。一般是用于为算法提供策略。当对象和()结合会触发重载函数调用运算符。

#include <iostream>
using namespace std;

class Print
{

public:
    """函数调用重载运算符"""
    void operator()(char* str)
        {
            cout << str << endl;
        }
};

int main()
{
        Print ob;
        ob("hello printf");  """这里Print()("hello world")也阔以,因为类名称和小括号结合时匿名对象,匿名对象也是对象,对象和小括号结合当然是也触发了重载函数调用运算符"""
        return 0;
}

六。智能指针

             用类包裹的指针叫智能指针。作用是系统能自动回收该指针指向的地址,所以才叫智能指针。

#include <iostream>
using namespace std;

class Data
{
public:
    Data()
        {
            cout << "Data的无参构造" << endl;
        }

    ~Data()
        {
            cout << "Data的析构函数" << endl;
        }
    void func()
        {
            cout << "Data的func函数" << endl;
        }
};

class SmartPointer
{
private:
     Data* p;
public:
     SmartPointer(){}
     SmartPointer(Data* p)
        {
            this->p = p;
        }
     ~SmartPointer()
        {
            delete p;
        }
     """重载->运算符"""
        Data* operator->()
        {
            return p;
        }
      """重载->运算符第二种"""
        Data& operator*()
        {
            return *p;
        }
        
};

int main()
{
    SmartPointer sp(new Data);
    sp->func();"""等价于sp.operator->()->func()"""
    """第二种"""
   """ (*sp).func();"""
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值