C语言学习笔记5:运算符重载

C语言学习笔记5:运算符重载,第1张

一:基本概念

c++中的运算符(+ - * / ....< >  ... << >> ...)可以直接作用于基本类型(char ,int ,double ..)和标准库定义的类型(string...)
但是这些运算符不能直接作用于我们自定义的数据类型, 这个时候就要重新赋予这些运算符新的功能,使之能够直接 *** 作我们自定义类型,这就是运算符重载。



c++中所有运算符重载都是使用函数实现的,所以运算符重载的本质就是函数重载。


运算符重载函数的格式如下:
 

  返回值类型 operator运算符号(参数列表)
    {
        具体代码
    }

    返回值类型:运算符的运算结果类型
    operator运算符号    ->相当于函数名
            比如: operator+
    参数列表:参数个数及参数类型
            参数个数:由该运算符所需要的 *** 作数的个数决定
            参数类型:你想要参与该运算符的数据类型(一定要至少包含一个自定义类型

如:

Mystring& Mystring::operator=(const Mystring& other) {
    /* 新功能函数体 */
}

二、运算符重载的限制 1、不能重载的运算符(常见的)

sizeof :    sizeof运算符
.      :    成员运算符
.*     :    成员指针运算符
::     :    作用域运算符
? :    :    三目运算符
2、不能使用友元函数,只能声明为成员函数的运算符
=     :    赋值运算符
[]    :    下标运算符
()    :    函数调用运算符
->    :    通过指针访问类成员的运算符

三、运算符重载的两种方式

一、重载为成员函数

以mstring类举例:

/* 拷贝赋值函数 */
Mystring& Mystring::operator=(const Mystring& other) {
    assert(this != &other);
    this->m_size = other.m_size;
    delete []this->m_ptr;
    this->m_ptr = new char[this->m_size + 1]{0};
    strcpy(this->m_ptr, other.m_ptr);

    return *this;
}

/* 移动拷贝赋值函数 */
Mystring& Mystring::operator=(Mystring&& other) {
    assert(this != &other);
    this->m_size = other.m_size;
    delete []this->m_ptr;
    this->m_ptr = other.m_ptr;
    other.m_ptr = nullptr;

    return *this;
}

二、重载为友元函数

1、在class类中生明
using std::ostream;
class Mystring {

    friend ostream& operator<<(ostream& out, const Mystring& other);

}

2、实现

ostream& operator<<(ostream& out, const Mystring& other) {
    out << other.m_ptr;
    return out;
}
ps:特殊点的运算符(前++和后++)

对于a本身而言没有区别,区别在于这个表达式的值不一样,a++这个表达式的值是a自增之前的值,
    ++a这个表达式的值是a自增之后的值。


    ++这个运算符有前++和后++之分,重载一次显然满足不了要求,-> 需要重载两次:
        后++ 要提供一个“占位形参”,该形参只是占一个位置,在函数中并不会用到它

   class Demo
        {
        public:
            Demo(int data = 0)
            {
                this->data = data;
            }

            Demo& operator++()//前++
            {
                data ++;
                return *this;
            }

            Demo operator++(int)//后++
            {
                Demo temp{data};
                data ++;
                return temp;
            }
        private:
            int data;
        }

        int main()
        {
            Demo d{10};
            ++d;
        }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/585000.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存