运算符在C ++中重载 [英] Operator Overloading in C++

查看:170
本文介绍了运算符在C ++中重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怀疑我们是否可以做以下事情。

I have doubt whether we can do the following or not.

假设我已经创建了 A ie obj1 obj2 和类 A 函数 show()

Suppose I have created two instance of class A i.e. obj1 and obj2 and class A has member function show().

我可以使用下列命令吗?

Can I use the following?

(obj1+obj2).show()

如果是,如何?如果没有,为什么不可能?

If yes, how? If no, why it is not possible?

推荐答案

是的,有可能,只需实现operator + for A并返回一个类类型A:

Yes it is possible, just implement operator+ for A and have it return a class of type A:

#include <iostream>

class A
{
public:
    explicit A(int v) : value(v) {}

    void show() const { std::cout << value << '\n'; }

    int value;
};

A operator+(const A& lhs, const A& rhs)
{
    A result( lhs.value + rhs.value );
    return result;
}

int main()
{
    A a(1);
    A b(1);

    (a+b).show(); // prints 2!

    return 0;
}

这篇关于运算符在C ++中重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆