Abh*_*eet 4 c++ operator-overloading
我怀疑我们是否可以做以下事情.
假设我已经创建类的两个实例A,即obj1和obj2和类A有成员函数show().
我可以使用以下内容吗?
(obj1+obj2).show()
Run Code Online (Sandbox Code Playgroud)
如果有,怎么样?如果不是,为什么不可能呢?
是的,这是可能的,只需为A实现operator +并让它返回类型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;
}
Run Code Online (Sandbox Code Playgroud)