operator=、operator[]、operator()操作符重载

本文聚焦C++运算符重载。介绍了赋值运算符=、[]和函数调用符()的重载,如=重载用于对象数据复制,需释放旧内存、分配新内存并赋值;[]用于访问元素,()用于函数调用。还阐述了不要重载&&和||操作符的原因,因其内置短路规则,重载无法实现。

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

重载赋值运算符=

  • 赋值运算符重载用于对象数据的复制
  •  operator= 必须重载为成员函数
  • 重载函数原型为:类型  &  类名  :: operator= ( const  类名 & ) ; 
#pragma warning(disable : 4996)
#include <iostream>
using namespace std;

class Name
{
public:
    Name(const char* c)
    {
        len = strlen(c);
        this->m_name = new char[len + 1];
        strcpy(this->m_name, c);
        cout << "构造函数" << endl;
    }
    //返回值当左值需要返回一个引用
    Name &operator=(const Name &n)
    {
        //先释放旧的内存
        if (this->m_name != NULL)
        {
            delete[] m_name;
            len = 0;
        }
        //根据新的对象分配新的内存大小
        len = n.len;
        this->m_name = new char[len+1];
        //把新的值赋值给当前变量
        strcpy(this->m_name, n.m_name);
        return *this;
    }

    void GetName()
    {
        cout << "Name = " << m_name << endl;
    }

    ~Name() 
    {
        cout << "析构函数" << endl;
    }
private:
    char *m_name;
    int len;
};

void PlayObj()
{
    Name n1("ZhangSan");
    n1.GetName();
    Name n2("WangWu");
    n2.GetName();
    Name n3 = "LiSi";
    n3.GetName();

    n3 = n2 = n1;
    n3.GetName();
}

int main()
{
    PlayObj();
    system("pause");
    return 0;
}

重载=操作符的步骤:

1、释放当前旧的内存

2、根据新的对象分配新的内存大小

3、把新的值赋值给当前变量

重载赋值运算符[]

  • 运算符 [] 和 () 是二元运算符
  •  [] 和 () 只能用成员函数重载,不能用友元函数重载

[] 运算符用于访问数据对象的元素,重载格式 类型  类 :: operator[]  ( 类型 ) ;

class Vector
{
public:
    Vector(int n)
    {
        size = n;
        v = new int[size];
    }
    int & operator[](int n)
    {
        return v[n];
    }

    ~Vector()
    {
        delete[] v;
        size = 0;
    }
private:
    int *v;
    int size;
};

void PlayObj()
{
    Vector v(5);
    for (int i = 0; i < 5; i++)
    {
        v[i] = i + 1;
    }

    cout << "v[3] = " << v[3] << endl;
}

int main()
{
    PlayObj();
    system("pause");
    return 0;
}
 v[i] = i + 1;

看上面的语句,v[i]作左值,因此需要返回一个引用。

重载函数调用符 ()

  • 运算符 [] 和 () 是二元运算符
  •  [] 和 () 只能用成员函数重载,不能用友元函数重载

() 运算符用于函数调用,重载格式 类型  类 :: operator()  ( 表达式表  ) ;

class Complex
{
public:
    double FunAddr(double x, double y)
    {
        return x * x + y * y;
    }

    double operator()(double x, double  y)
    {
        return x * x + y * y;
    }
};

void PlayObj()
{
    Complex c;
    cout << "Addr = " << c.FunAddr(2.5, 3.5) << endl;
    cout << "Addr = " << c(2.5, 3.5) << endl;
}

int main()
{
    PlayObj();
    system("pause");
    return 0;
}

为什么不要重载&&和||操作符

1、&&和||是C++中非常特殊的操作符

2、&&和||内置实现了短路规则

3、操作符重载是靠函数重载来完成的

4、操作数作为函数参数传递

5、C++的函数参数都会被求值,无法实现短路规则

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值