重载plus运算符的正确方法是什么?

时间:2015-04-25 15:36:27

标签: c++ c++11 operator-overloading

我有一组课程:

class A 
{
public:
    A(B b) {//..}   
    A(C C) {//..}
    A(D D) {//..}

    A& operator+=(A const& ls) {//..}
    A operator+(A const& ls) const {//..}
}

class B
{
//....
}

class C
{
//....
}

class D
{
//....
}

我想支持以下操作:

1) A result = a1 + a2;
2) a1 += a2;
3) A result = b1 + a1; (and C, D classes instead of B)
4) A result = a1 + b1; (and C, D classes instead of B)
5) a1 += b1; (and C, D classes instead of B)

在这种情况下如何做?我不想使用boost

1 个答案:

答案 0 :(得分:3)

您缺少的是B的LHS CDAoperator+的隐式转换。您可以通过使运算符成为非成员函数来允许此操作。例如:

A operator+(A const& ls, A const& rs)
{
  A ret = ls;
  ret += rs;
  return ret;
}