运算符重载

一、概念

1、运算符重载,本质上是编写以运算符作为函数名的函数

返回值类型  operate 运算符 (形参列表)
{
    ...
}

运算符的操作数成为运算符函数调用的实参运算的结果就是运算符函数的返回值

2、运算符可以被重载为全局函数,也可以被重载为成员函数

class Element
{
public:
    Element(int i, double d);
public:
    int id;
    double val;
    Element operator - (const Element& c);
};
 // 运算符被重载为成员函数
Element Element::operator - (const Element& c) 
{
    Element temp = Element(id - c.id, val - c.val);
    return temp;
}
// 运算符被重载为全局函数
Element operator + (const Element& c1, const Element& c2)  
{
    Element temp = Element(c1.id + c2.id, c1.val + c2.val);
    return temp;
}
// 运算符被重载为全局函数时,参数的个数,等于运算符的目数(即操作数的个数)
// 运算符被重载为成员函数时,参数的个数等于运算符目数-1

3、浅拷贝和深拷贝

比如string 中的 str 成员,指向的是string 对象字符存储的地方

class string
{
    ...
    char* str[];   // 指向的是字符数组存储的空间
}

string s1 = "this";
string s2 = "that";
s2 = s1;   // 该处执行的是浅拷贝,此时s2.str 和 s1.str 都指向同一块内存
// 当出了两个的定义域,这块内存会被释放两次
// 深拷贝的写法,重载赋值运算符
string & string::operator= (const string& s)
{
    if (str == s.str)  // 当时自身时
        return this;
    if (str)
        delete[] str;  //  先释放自身的空间
    if (s.str)    // 当s.str 不为空时,才执行复制操作
    {
        str = new char[strlen(s.str) + 1];
        strcpy(str.s.str);
    }
    else
        str = nullptr;
    return *this;
}

 

posted @ 2020-06-07 16:56  min_zhi  阅读(156)  评论(0)    收藏  举报