运算符重载

运算符重载

重载运算符

重载一元负运算符
Counter operator-() const {
        return Counter(-count);
 }
   

    // 重载逻辑非运算符
    bool operator!() const {
        return count == 0;
    }

    int getValue() const {
        return count;
    }
};
二元运算符重载(例如: + ,  - ,  * ,  / ,  == ,  <:
class Point {
private:
    int x, y;
public:
    Point(int x = 0, int y = 0) : x(x), y(y) {}

    // 重载加法运算符
    Point operator+(const Point& rhs) const {
        return Point(x + rhs.x, y + rhs.y);
    }

    // 重载减法运算符
    Point operator-(const Point& rhs) const {
        return Point(x - rhs.x, y - rhs.y);
    }

    // 重载乘法运算符,表示点的面积
    int operator*(const Point& rhs) const {
        return x * rhs.y - y * rhs.x;
    }

    // 重载除法运算符
    Point operator/(int divisor) const {
        return Point(x / divisor, y / divisor);
    }

    // 重载等于运算符
    bool operator==(const Point& rhs) const {
        return (x == rhs.x) && (y == rhs.y);
    }

    // 重载小于运算符
    bool operator<(const Point& rhs) const {
        return x < rhs.x || (x == rhs.x && y < rhs.y);
    }
};
赋值运算符重载(例如: =:
class Matrix {
private:
    int rows, cols;
    int* data;
public:
    // 构造函数、析构函数等...

    // 重载赋值运算符
    Matrix& operator=(const Matrix& other) {
        if (this != &other) {
            // 释放当前矩阵的内存
            // 重新分配内存并复制数据
        }
        return *this;
    }
};
函数调用运算符重载( ():
class Calculator {
public:
    int value;

    // 重载函数调用运算符
    int operator()(int x) {
        return value + x;
    }
};
下标运算符重载( []:
class Array {
private:
    int* data;
    int size;
public:
    // 构造函数、析构函数等...

    // 重载下标运算符
    int& operator[](int index) {
        return data[index];
    }

    const int& operator[](int index) const {
        return data[index];
    }
};
成员访问箭头运算符重载( ->:
class Handle {
private:
    int* ptr;
public:
    Handle(int* p) : ptr(p) {}

    // 重载箭头运算符
    int* operator->() {
        return ptr;
    }
};
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值