20220704函数重载、加法运算符重载

1.全局函数重载

#include<iostream>
using namespace std;
#include<string>

class person{
    public:
        int m_a;
        int m_b;
};
person operator+(person &p1,person &p2){
    person temp;
    temp.m_a=p1.m_a+p2.m_a;
    temp.m_b=p1.m_a+p2.m_b;
    return temp;
}
void test01(){
    person p1;
    p1.m_a=10;
    p1.m_b=10;
    person p2;
    p2.m_a=20;
    p2.m_b=20;
    
    person p3=p1 + p2;
    cout<<"p3.m_a:"<<p3.m_a<<endl;
    cout<<"p3.m_b:"<<p3.m_b<<endl; 
}
//全局函数重载 

int main(){
    test01();
    return 0;
}

2.成员函数重载

person operator+(person &p){
    person temp;
    temp.m_a=this->m_a+p.m_a;
    temp.m_b=this->m_a+p.m_b;
    return temp;
}

3.函数重载

person operator+(person &p1,int num){
    person temp;
    temp.m_a=p1.m_a+num;
    temp.m_b=p1.m_a+num;
    return temp;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C++ 中,可以通过重载加法运算符来实现自定义类型的相加操作。重载加法运算符的语法如下: ```cpp 返回值类型 operator+(const 类型名& 参数名) { // 实现相加操作的代码 } ``` 其中,`operator+` 表示重载加法运算符,返回值类型为相加结果的类型,`类型名` 是相加操作的另一个操作数的类型名,`参数名` 是相加操作的另一个操作数的名称。在函数体中,可以实现相加操作,并返回相加结果。 下面是一个例子,演示如何在 C++ 中重载加法运算符: ```cpp #include <iostream> class Complex { public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} Complex operator+(const Complex& other) const { Complex result; result.real = real + other.real; result.imag = imag + other.imag; return result; } void display() const { std::cout << "(" << real << ", " << imag << ")" << std::endl; } private: double real; double imag; }; int main() { Complex c1(1, 2), c2(3, 4), c3; c3 = c1 + c2; c3.display(); // 输出 (4, 6) return 0; } ``` 在上面的例子中,我们定义了一个复数类 `Complex`,并重载加法运算符 `operator+`,使得 `Complex` 类型的对象可以相加。在 `operator+` 函数中,我们实现了两个复数对象的相加操作,并返回相加结果。在 `main` 函数中,我们创建了两个复数对象 `c1` 和 `c2`,并将它们相加,将结果赋值给 `c3`。最后调用 `c3.display()` 函数输出相加结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值