operator重载运算符

文章详细介绍了C++中的运算符重载,展示了如何重载加法运算符(二元运算符)、一元运算符(如自增)以及括号运算符。通过示例代码,解释了如何在自定义类中定义这些运算符的行为,使得它们能适用于特定的数据类型。
摘要由CSDN通过智能技术生成

在C++中,operator是一个关键字,用于定义和重载运算符。运算符重载是C++的一个强大特性,允许你重新定义内置的运算符,以便它们适用于自定义的数据类型或类对象。最后return是你运算完之后返回的值。

重载加法(二元)运算符:

class Point {
private:
    int x;
    int y;

public:
    Point(int xCoord, int yCoord) : x(xCoord), y(yCoord) {}  //构造函数

    Point operator+(const Point& other) {  //因为是二元运算符、所以这里
        return Point(x + other.x, y + other.y);
    }
};


int main(){
Point p1(2, 3);
Point p2(4, 5);
Point result = p1 + p2;
}

重载一元运算符

class Counter {
private:
    int count;

public:
    Counter(int initialCount) : count(initialCount) {}

    Counter operator++() {
        ++count;
        return *this;
    }
};

int main(){
    Counter c(5);
    ++c;
}

重载()括号:

class person{
public:
    person(int a,int b){
        printf("%d\n",a+b);
    }
    void operator()(int a,int b){
        printf("%d\n",a+2*b);
    }
};

int main()
{
    person p(1,2);
    p(1,3);

    return 0;
}

 可以看到在声明函数的时候的括号并不会触发operator。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值