zoukankan      html  css  js  c++  java
  • C语言运算符重载

    就是改变原来运算符的一些性质,也就是给运算符重新定义它的功能。

    例子:比如编译器自己形成的浅拷贝构造函数可能会导致析构函数引发内存多次释放而引起内存错误,那么归根到底是由于赋值操作出了问题,那么我们可以针对类,单独对“=”进行运算符重载,解决浅拷贝可能引发的问题。

    class CSstudent{
    public:
    char* p_name;
    char sex;
    int age;
    int num;
         CStudent& operator=(const CStudent& stud);//重新定义=,即重载运算符=,此=只对CSstudent类起效果

    }


    CStudent& CStudent::operator=(const CStudent& stud) {     if (p_name)     {         delete[] p_name;         p_name = NULL;     }     int name_len = strlen(stud.p_name) + 1;     p_name = new char[name_len];     memset(p_name, 0, name_len);     strcpy(p_name, stud.p_name);     sex = stud.sex;     num = stud.num;     age = stud.age;     return *this; }
    穷则独善其身,达则兼济天下……
  • 相关阅读:
    6.11 修饰符的适用范围
    5.10 对象与垃圾回收
    5.9 枚举类
    5.8 java 11增强的Lambda表达式
    5.7 内部类
    5.6 接口
    5.5 抽象类
    5.4 final修饰符
    5.3 类成员
    5.2 Object类中两个需要被重写的方法
  • 原文地址:https://www.cnblogs.com/hmy-666/p/14414119.html
Copyright © 2011-2022 走看看