c++重载

函数或运算符重载是指在同一作用域内定义多个具有相同名称但参数类型或数量不同的函数或运算符。重载允许使用相同的名称执行不同的操作,具体的操作根据传递给函数或运算符的参数类型或数量而定。(和Java重载一样直接和Java重载联系到一起)大致分为两类函数和运算符的重载

函数重载: 允许在同一作用域内定义多个具有相同名称但参数列表不同的函数。例如:

1
2
3
4
5
6
7
int add(int a, int b) {
    return a + b;
}
 
double add(double a, double b) {
    return a + b;
}

运算符重载: 允许在用户定义的类中重新定义运算符的行为。例如: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Complex {
public:
    double real;
    double imag;
 
    Complex operator+(const Complex& other) const {
        Complex result;
        result.real = real + other.real;
        result.imag = imag + other.imag;
        return result;
    }
};
 
int main() {
    Complex c1 = {1.0, 2.0};
    Complex c2 = {3.0, 4.0};
    Complex result = c1 + c2;  // 通过运算符重载执行复数的加法
    return 0;
}

  下面就写一下运算符重载,因为刚好做到阶乘的和通过高精度算法来求,格式(下面的是全局函数重载,有个成员函数重载的就先不管了)

1
2
3
返回类型 operator运算符(参数列表) {
    // 运算符的实现
}<br>

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
 
class MyClass {
public:
    int value;
 
    MyClass(int val) : value(val) {}
};
 
// 全局函数重载 + 运算符
MyClass operator+(const MyClass& obj1, const MyClass& obj2) {
    MyClass result;
    result.value = obj1.value + obj2.value;
    return result;
}
 
int main() {
    // 步骤 1: 创建类的对象
    MyClass obj1(5);
    MyClass obj2(10);
 
    // 步骤 2: 使用函数名和对象调用全局函数重载运算符
    MyClass result = operator+(obj1, obj2);
 
    // 输出结果
 cout << "Result: " << result.value << endl;
 
    return 0;
}

  

 

posted @   zhongjx13  阅读(15)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示