C++ 运算符重载


运算符重载的本质是函数重载。

1. 语法格式

返值类型 operator 运算符名称(形参表列)
{
	重载实体;
}

operator 运算符名称 在一起构成了新的函数名。比如
const Complex operator+(const Complex &c1,const Complex &c2);
我们会说,operator+ 重载了重载了运算符+。

1.1 友元重载

#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(float x=0, float y=0):_x(x),_y(y){}
    void dis()
    {
        cout<<"("<<_x<<","<<_y<<")"<<endl;
    }
friend const Complex operator+(const Complex &c1,const Complex &c2);
private:
    float _x;
    float _y;
};
const Complex operator+(const Complex &c1,const Complex &c2)
{
    return Complex(c1._x + c2._x,c1._y + c2._y);
}
int main()
{
    Complex c1(2,3);
    Complex c2(3,4);
    c1.dis();
    c2.dis();
    // Complex c3 = c1+c2;
    Complex c3 = operator+(c1,c2);
    c3.dis();
    return 0;
}

输出结果

1.2 成员重载

#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(float x=0, float y=0):_x(x),_y(y){}
    void dis()
    {
        cout<<"("<<_x<<","<<_y<<")"<<endl;
    }
friend const Complex operator+(const Complex &c1,const Complex &c2);
const Complex operator+(const Complex &another);
private:
    float _x;
    float _y;
};
const Complex operator+(const Complex &c1,const Complex &c2)
{
    cout<<"友元函数重载"<<endl;
    return Complex(c1._x + c2._x,c1._y + c2._y);
}
const Complex Complex::operator+(const Complex & another)
{
    cout<<"成员函数重载"<<endl;
    return Complex(this->_x + another._x,this->_y + another._y);
}
int main()
{
    Complex c1(2,3);
    Complex c2(3,4);
    c1.dis();
    c2.dis();
    // Complex c3 = c1+c2;
    // Complex c3 = operator+(c1,c2);
    Complex c3 = c1+c2; //优先调用成员函数重载??
    c3.dis();
    return 0;
}

输出结果

1.3 注意事项

关于运算符重载函数的返回值:
int a = 3;
int b = 4;
(a+b) = 100; 这种语法是错的,所以重载函数+的返回值加 const 是来修饰。
string a = “china”,b = “ is china”, c;
(c = a) = b; 此时的语法,是重载= 返回值不需加 const 。

2. 重载规则

  1. C++不允许用户自己定义新的运算符,只能对已有的 C++运算符进行重载。
  2. C++允许重载的运算符在这里插入图片描述
  3. 不能重载的运算符在这里插入图片描述
  4. 重载不能改变运算符运算对象(即操作数)的个数。
  5. 重载不能改变运算符的优先级别。
  6. 重载不能改变运算符的结合性。如,复制运算符”=“是右结合性(自右至左),重载后仍为右结合性。
  7. 重载运算符的函数不能有默认的参数,否则就改变了运算符参数的个数,与前面矛盾。
  8. 重载运算符的运算中至少有一个操作数是自定义类。重载的运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应有一个是类对象(或类对象的引用)。也就是说,参数不能全部是 C++的标准类型,以防止用户修改用于标准类型数据成员的运算符的性质。

3. 双目运算符重载

3.1 成员函数重载+=实现

using namespace std;
class Complex
{
public:
    Complex(float x=0, float y=0):_x(x),_y(y){}
    void dis()
    {
        cout<<"("<<_x<<","<<_y<<")"<<endl;
    }
    Complex& operator+=(const Complex &c)
    {
        this->_x += c._x;
        this->_y += c._y;
        return * this;
    }
private:
    float _x;
    float _y;
};
int main()
{

    int a = 10, b = 20,c = 30;
    (a += b) += c;
    cout<<"a = "<<a<<endl;
    cout<<"b = "<<b<<endl;
    cout<<"c = "<<c<<endl;
    Complex a1(10,0),b1(20,0), c1(30,0);
    (a1 += b1) += c1;
    a1.dis();
    b1.dis();
    c1.dis();
    return 0;
}

在这里插入图片描述

3.2 友元函数重载+=实现

friend Complex& operator-=(Complex &c1, const Complex & c2)
{
}

4. 单目运算符重载

4.1 友元函数重载++(前++)实现

#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(float x=0, float y=0):_x(x),_y(y){}
    void dis()
    {
        cout<<"("<<_x<<","<<_y<<")"<<endl;
    }
friend Complex & operator++(Complex& c);
private:
    float _x;
    float _y;
};
Complex& operator++(Complex& c)
{
    c._x++;
    c._y++;
    return c;
}
int main()
{
    int n = 10;
    cout<<n<<endl; //10
    cout<<++n<<endl; //11
    cout<<n<<endl; //11
    cout<<++++n<<endl; //13
    cout<<n<<endl; //13
    Complex c(10,10);
    c.dis(); //10 10
    Complex c2=++c;
    c2.dis(); //11 11
    c.dis(); //11 11
    c2 = ++++c;
    c2.dis(); //13 13
    c.dis(); //13 13
    return 0;
}

输出结果

4.2 友元函数重载++(后++)实现

#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(float x=0, float y=0):_x(x),_y(y){}
    void dis()
    {
        cout<<"("<<_x<<","<<_y<<")"<<endl;
    }
friend const Complex operator++(Complex &c,int);
private:
    float _x;
    float _y;
};
const Complex operator++(Complex &c,int)
{
    Complex t(c._x,c._y);
    c._x++;
    c._y++;
    return t;
}
int main()
{
    int n = 10;
    cout<<n<<endl; //10
    cout<<n++<<endl; //10
    cout<<n<<endl; //11
    // cout<<n++++<<endl; //13 后++表达式不能连用
    cout<<n<<endl; //11
    Complex c(10);
    c.dis();
    Complex c2 = c++;
    c2.dis();
    c.dis();
    // c2 = c++++; //error
    // c2.dis();
    return 0;
}

输出结果

4. 友元还是成员

1,一个操作符的左右操作数不一定是相同类型的对象,这就涉及到将该操作符函数定义为谁的友元,谁的成员问题。
2,一个操作符函数,被声明为哪个类的成员,取决于该函数的调用对象(通常是左操作数)。
3,一个操作符函数,被声明为哪个类的友员,取决于该函数的参数对象(通常是右操作数)。

假设,我们有类 Sender 类和 Mail 类,实现发送邮件的功能

Sender sender; Mail mail;
sender<< mail

sender 左操作数,决定了 operator<<为 Sender 的成员函数,而 mail 决定了operator<<要作 Mail 类的友员。

#include <iostream>
using namespace std;
class Mail;
class Sender
{
public:
    Sender(string s):_addr(s){}
    Sender& operator<<(const Mail & mail); //成员
private:
    string _addr;
};
class Mail
{
public:
    Mail(string _t,string _c ):_title(_t),_content(_c){}
    friend Sender& Sender::operator<<(const Mail & mail);
//友元
private:
    string _title;
    string _content;
};
Sender& Sender::operator<<(const Mail & mail)
{
    cout<<"Address:"<<_addr<<endl;
    cout<<"Title :"<<mail._title<<endl;
    cout<<"Content:"<<mail._content<<endl;
    return *this;
}
int main()
{
    Sender sender("17873567239@139.com");
    Mail mail("reply","yes");
    Mail mail2("time","9pm");
    sender<<mail<<mail2;
    return 0;
}

输出结果

<think>好的,我现在要帮用户介绍C++运算符重载。首先,我需要回忆一下运算符重载的基本概念。运算符重载允许用户自定义类型使用C++内置的运算符,比如+、-、*等,使得代码更直观和易读。例如,可以让两个对象直接相加,而不必调用特定的函数。 接下来,我应该考虑用户可能的背景。用户可能是刚开始学习C++,或者已经有一定基础但想深入了解运算符重载。因此,解释需要清晰,从基础开始,逐步深入。可能需要先说明什么是运算符重载,为什么需要它,然后讲解如何实现,包括语法和注意事项。 然后,运算符重载的语法是关键部分。需要详细说明如何定义运算符重载函数,包括成员函数和非成员函数(友元函数)的区别。例如,重载+运算符时,成员函数通常只需要一个参数,因为左操作数是对象本身,而非成员函数需要两个参数。同时,要提到一些运算符必须作为成员函数重载,比如赋值运算符=。 例子是帮助理解的重要部分。我应该举一个简单的例子,比如为自定义的Vector类重载+运算符,这样用户可以看到具体的实现方式。同时,需要区分成员函数和非成员函数的例子,说明它们的不同应用场景。 注意事项和常见问题也不能遗漏。比如不能重载运算符(如.、::、sizeof等),以及重载时保持运算符的原有语义,避免滥用导致代码难以理解。此外,还需要提到运算符的返回类型和参数类型的选择,比如是否返回引用或值,参数的const修饰等。 用户可能还会有疑问,比如运算符重载的使用场景,或者何时应该使用成员函数而非友元函数。因此,在解释过程中需要涵盖这些方面,可能的话,给出一些最佳实践的建议。 最后,总结运算符重载的优点和需要注意的地方,帮助用户全面理解。确保语言通俗易懂,避免过于专业的术语,必要时进行类比,让用户更容易接受。</think>### C++运算符重载详解 #### 1. 什么是运算符重载运算符重载(Operator Overloading)是C++中的一种特性,允许开发者**为自定义类型(如类或结构体)重新定义运算符的行为**。通过重载运算符,可以让对象像内置类型(如`int`、`double`)一样使用`+`、`-`、`*`、`==`等运算符,提升代码可读性和简洁性。 --- #### 2. 如何实现运算符重载运算符重载通过**成员函数**或**全局函数**实现,语法形式为: $$ \text{返回类型 operator 运算符(参数列表)} $$ ##### 示例1:成员函数重载`+` ```cpp class Vector { public: int x, y; // 成员函数重载 + Vector operator+(const Vector& other) { return {x + other.x, y + other.y}; } }; // 使用 Vector v1{1, 2}, v2{3, 4}; Vector v3 = v1 + v2; // 等价于 v1.operator+(v2) ``` ##### 示例2:全局函数重载`<<`(输出流) ```cpp class Student { public: string name; int age; }; // 全局函数重载 << ostream& operator<<(ostream& os, const Student& s) { os << "Name: " << s.name << ", Age: " << s.age; return os; } // 使用 Student s{"Alice", 20}; cout << s; // 输出: Name: Alice, Age: 20 ``` --- #### 3. 常见运算符重载规则 | 运算符类型 | 可重载性 | 示例 | |------------------|----------------|----------------------| | 算术运算符 | `+`, `-`, `*` | `a + b` | | 关系运算符 | `==`, `>`, `<` | `a == b` | | 赋值运算符 | `=`, `+=` | `a = b` | | 下标运算符 | `[]` | `a[0]` | | 函数调用运算符 | `()` | `a(1, 2)` | | **不可重载运算符** | `.`、`::`、`?:`、`sizeof` | 无法重载 | --- #### 4. 关键注意事项 1. **参数限制**: - 至少一个操作数是用户自定义类型(不能全为内置类型)。 - 不能修改运算符的优先级或结合性。 2. **成员函数 vs 全局函数**: - 赋值运算符(`=`)、下标运算符(`[]`)、函数调用运算符(`()`)**必须**作为成员函数重载。 - 输入输出运算符(`>>`、`<<`)通常作为全局函数。 3. **保持语义一致性**: - 例如重载`+`时,不应修改操作数本身,而应返回新对象。 --- #### 5. 完整示例:复数类重载 ```cpp class Complex { private: double real, imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} // 成员函数重载 + Complex operator+(const Complex& other) { return Complex(real + other.real, imag + other.imag); } // 全局友元函数重载 << friend ostream& operator<<(ostream& os, const Complex& c); }; ostream& operator<<(ostream& os, const Complex& c) { os << c.real << " + " << c.imag << "i"; return os; } // 使用 Complex c1(2, 3), c2(4, 5); Complex c3 = c1 + c2; cout << c3; // 输出: 6 + 8i ``` --- #### 6. 应用场景 - 数学计算(向量、矩阵、复数) - 字符串操作(`str1 + str2`) - 容器类(自定义数组、链表) --- #### 7. 总结 **优点**:提升代码直观性,使自定义类型操作更自然。 **注意**:避免过度使用或违反直觉的重载(例如用`+`实现减法)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值