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

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

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

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 

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/873967.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存