C++运算符重载

#include <iostream>
#include <cmath>
using namespace std;
//复数类
class Complex{
public:  //构造函数
    Complex(double real = 0.0, double imag = 0.0): m_real(real), m_imag(imag){ }
public:  //运算符重载
    //以全局函数的形式重载
    friend Complex operator+(const Complex &c1, const Complex &c2);
    friend Complex operator-(const Complex &c1, const Complex &c2);
    friend Complex operator*(const Complex &c1, const Complex &c2);
    friend Complex operator/(const Complex &c1, const Complex &c2);
    friend bool operator==(const Complex &c1, const Complex &c2);
    friend bool operator!=(const Complex &c1, const Complex &c2);
    //以成员函数的形式重载
    Complex & operator+=(const Complex &c);
    Complex & operator-=(const Complex &c);
    Complex & operator*=(const Complex &c);
    Complex & operator/=(const Complex &c);
public:  //成员函数
    double real() const{ return m_real; }
    double imag() const{ return m_imag; }
private:
    double m_real;  //实部
    double m_imag;  //虚部
};
//重载+运算符
Complex operator+(const Complex &c1, const Complex &c2){
    Complex c;
    c.m_real = c1.m_real + c2.m_real;
    c.m_imag = c1.m_imag + c2.m_imag;
    return c;
}
//重载-运算符
Complex operator-(const Complex &c1, const Complex &c2){
    Complex c;
    c.m_real = c1.m_real - c2.m_real;
    c.m_imag = c1.m_imag - c2.m_imag;
    return c;
}
//重载*运算符  (a+bi) * (c+di) = (ac-bd) + (bc+ad)i
Complex operator*(const Complex &c1, const Complex &c2){
    Complex c;
    c.m_real = c1.m_real * c2.m_real - c1.m_imag * c2.m_imag;
    c.m_imag = c1.m_imag * c2.m_real + c1.m_real * c2.m_imag;
    return c;
}
//重载/运算符  (a+bi) / (c+di) = [(ac+bd) / (c²+d²)] + [(bc-ad) / (c²+d²)]i
Complex operator/(const Complex &c1, const Complex &c2){
    Complex c;
    c.m_real = (c1.m_real*c2.m_real + c1.m_imag*c2.m_imag) / (pow(c2.m_real, 2) + pow(c2.m_imag, 2));
    c.m_imag = (c1.m_imag*c2.m_real - c1.m_real*c2.m_imag) / (pow(c2.m_real, 2) + pow(c2.m_imag, 2));
    return c;
}
//重载==运算符
bool operator==(const Complex &c1, const Complex &c2){
    if( c1.m_real == c2.m_real && c1.m_imag == c2.m_imag ){
        return true;
    }else{
        return false;
    }
}
//重载!=运算符
bool operator!=(const Complex &c1, const Complex &c2){
    if( c1.m_real != c2.m_real || c1.m_imag != c2.m_imag ){
        return true;
    }else{
        return false;
    }
}
//重载+=运算符
Complex & Complex::operator+=(const Complex &c){
    this->m_real += c.m_real;
    this->m_imag += c.m_imag;
    return *this;
}
//重载-=运算符
Complex & Complex::operator-=(const Complex &c){
    this->m_real -= c.m_real;
    this->m_imag -= c.m_imag;
    return *this;
}
//重载*=运算符
Complex & Complex::operator*=(const Complex &c){
    this->m_real = this->m_real * c.m_real - this->m_imag * c.m_imag;
    this->m_imag = this->m_imag * c.m_real + this->m_real * c.m_imag;
    return *this;
}
//重载/=运算符
Complex & Complex::operator/=(const Complex &c){
    this->m_real = (this->m_real*c.m_real + this->m_imag*c.m_imag) / (pow(c.m_real, 2) + pow(c.m_imag, 2));
    this->m_imag = (this->m_imag*c.m_real - this->m_real*c.m_imag) / (pow(c.m_real, 2) + pow(c.m_imag, 2));
    return *this;
}
int main(){
    Complex c1(25, 35);
    Complex c2(10, 20);
    Complex c3(1, 2);
    Complex c4(4, 9);
    Complex c5(34, 6);
    Complex c6(80, 90);
   
    Complex c7 = c1 + c2;
    Complex c8 = c1 - c2;
    Complex c9 = c1 * c2;
    Complex c10 = c1 / c2;
    cout<<"c7 = "<<c7.real()<<" + "<<c7.imag()<<"i"<<endl;
    cout<<"c8 = "<<c8.real()<<" + "<<c8.imag()<<"i"<<endl;
    cout<<"c9 = "<<c9.real()<<" + "<<c9.imag()<<"i"<<endl;
    cout<<"c10 = "<<c10.real()<<" + "<<c10.imag()<<"i"<<endl;
   
    c3 += c1;
    c4 -= c2;
    c5 *= c2;
    c6 /= c2;
    cout<<"c3 = "<<c3.real()<<" + "<<c3.imag()<<"i"<<endl;
    cout<<"c4 = "<<c4.real()<<" + "<<c4.imag()<<"i"<<endl;
    cout<<"c5 = "<<c5.real()<<" + "<<c5.imag()<<"i"<<endl;
    cout<<"c6 = "<<c6.real()<<" + "<<c6.imag()<<"i"<<endl;
   
    if(c1 == c2){
        cout<<"c1 == c2"<<endl;
    }
    if(c1 != c2){
        cout<<"c1 != c2"<<endl;
    }
   
    return 0;
}
运行结果:
c7 = 35 + 55i
c8 = 15 + 15i
c9 = -450 + 850i
c10 = 1.9 + -0.3i
c3 = 26 + 37i
c4 = -6 + -11i
c5 = 220 + 4460i
c6 = 5.2 + 1.592i
c1 != c2

C++ 规定,箭头运算符->、下标运算符[ ]、函数调用运算符( )、赋值运算符=只能以成员函数的形式重载。

#include <iostream>
using namespace std;
class complex{
public:
    complex(double real = 0.0, double imag = 0.0): m_real(real), m_imag(imag){ };
public:
    friend complex operator+(const complex & A, const complex & B);
    friend complex operator-(const complex & A, const complex & B);
    friend complex operator*(const complex & A, const complex & B);
    friend complex operator/(const complex & A, const complex & B);
    friend istream & operator>>(istream & in, complex & A);
    friend ostream & operator<<(ostream & out, complex & A);
private:
    double m_real;  //实部
    double m_imag;  //虚部
};
//重载加法运算符
complex operator+(const complex & A, const complex &B){
    complex C;
    C.m_real = A.m_real + B.m_real;
    C.m_imag = A.m_imag + B.m_imag;
    return C;
}
//重载减法运算符
complex operator-(const complex & A, const complex &B){
    complex C;
    C.m_real = A.m_real - B.m_real;
    C.m_imag = A.m_imag - B.m_imag;
    return C;
}
//重载乘法运算符
complex operator*(const complex & A, const complex &B){
    complex C;
    C.m_real = A.m_real * B.m_real - A.m_imag * B.m_imag;
    C.m_imag = A.m_imag * B.m_real + A.m_real * B.m_imag;
    return C;
}
//重载除法运算符
complex operator/(const complex & A, const complex & B){
    complex C;
    double square = A.m_real * A.m_real + A.m_imag * A.m_imag;
    C.m_real = (A.m_real * B.m_real + A.m_imag * B.m_imag)/square;
    C.m_imag = (A.m_imag * B.m_real - A.m_real * B.m_imag)/square;
    return C;
}
//重载输入运算符
istream & operator>>(istream & in, complex & A){
    in >> A.m_real >> A.m_imag;
    return in;
}
//重载输出运算符
ostream & operator<<(ostream & out, complex & A){
    out << A.m_real <<" + "<< A.m_imag <<" i ";;
    return out;
}
int main(){
    complex c1, c2, c3;
    cin>>c1>>c2;
    c3 = c1 + c2;
    cout<<"c1 + c2 = "<<c3<<endl;
    c3 = c1 - c2;
    cout<<"c1 - c2 = "<<c3<<endl;
    c3 = c1 * c2;
    cout<<"c1 * c2 = "<<c3<<endl;
    c3 = c1 / c2;
    cout<<"c1 / c2 = "<<c3<<endl;
    return 0;
}
运行结果:
2.4 3.64.8 1.7↙
c1 + c2 = 7.2 + 5.3 i
c1 - c2 = -2.4 + 1.9 i
c1 * c2 = 5.4 + 21.36 i
c1 / c2 = 0.942308 + 0.705128 i

下面我们通过一个具体的例子来演示如何重载[ ]。我们知道,有些较老的编译器不支持变长数组,例如 VC6.0、VS2010 等,这有时候会给编程带来不便,下面我们通过自定义的 Array 类来实现变长数组。

#include <iostream>
using namespace std;
class Array{
public:
    Array(int length = 0);
    ~Array();
public:
    int & operator[](int i);
    const int & operator[](int i) const;
public:
    int length() const { return m_length; }
    void display() const;
private:
    int m_length;  //数组长度
    int *m_p;  //指向数组内存的指针
};
Array::Array(int length): m_length(length){
    if(length == 0){
        m_p = NULL;
    }else{
        m_p = new int[length];
    }
}
Array::~Array(){
    delete[] m_p;
}
int& Array::operator[](int i){
    return m_p[i];
}
const int & Array::operator[](int i) const{
    return m_p[i];
}
void Array::display() const{
    for(int i = 0; i < m_length; i++){
        if(i == m_length - 1){
            cout<<m_p[i]<<endl;
        }else{
            cout<<m_p[i]<<", ";
        }
    }
}
int main(){
    int n;
    cin>>n;
    Array A(n);
    for(int i = 0, len = A.length(); i < len; i++){
        A[i] = i * 5;
    }
    A.display();
   
    const Array B(n);
    cout<<B[n-1]<<endl;  //访问最后一个元素
   
    return 0;
}
运行结果:
50, 5, 10, 15, 20
33685536

在 C++ 中进行运算符重载时,有以下问题需要注意:
重载后运算符的含义应该符合原有用法习惯。例如重载+运算符,完成的功能就应该类似于做加法,在重载的+运算符中做减法是不合适的。此外,重载应尽量保留运算符原有的特性。
C++ 规定,运算符重载不改变运算符的优先级。
以下运算符不能被重载:..*::? :sizeof
重载运算符()、[]、->、或者赋值运算符=时,只能将它们重载为成员函数,不能重载为全局函数。
运算符可以重载为全局函数,然后声明为类的友元。

<<和>>是在 iostream 中被重载,才成为所谓的“流插入运算符”和“流提取运算符”的。

类型的名字可以作为强制类型转换运算符,也可以被重载为类的成员函数。它能使得对象被自动转换为某种类型。

自增、自减运算符各有两种重载方式,用于区别前置用法和后置用法。

运算符重载不改变运算符的优先级。重载运算符时,应该尽量保留运算符原本的特性。

<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、付费专栏及课程。

余额充值