[C++]operator运算符重载 +, -, []

  1. +,- 运算符重载
#include <iostream>

class Complex{
public:
    Complex(int x, int y):a(x), b(y){};
    ~Complex(){};
    Complex operator - (const Complex &c);
    int a;
    int b;
};

Complex operator + (const Complex &x,  const Complex &y){
    return Complex(x.a + y.a, x.b + y.b);
}

Complex Complex::operator - (const Complex &c){
    a = a - c.a;
    b = b - c.b;
    return *this;
}

int main(){
    Complex test_a(8,9);
    Complex text_b(5,5);
    test_a = test_a - text_b;
    std::cout << test_a.a <<std::endl;
    std::cout << test_a.b <<std::endl;
    return 0;
}

运行结果:
3
4

  1. [] 运算符重载
#include <iostream>

class my_vertor{
public:
    my_vertor(){};
    ~my_vertor(){};
    int str[8] = {1,2,3,4,5,6,7,8};
    int operator [] (int x);
    int num;
};

int my_vertor::operator [](int x){
    return str[x];
}


int main(){
    my_vertor m_ver;
    std::cout<< m_ver[2] <<std::endl;
    return 0;
}

运行结果:
3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值