我有一组课程:
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
。
答案 0 :(得分:3)
您缺少的是B
的LHS C
,D
和A
到operator+
的隐式转换。您可以通过使运算符成为非成员函数来允许此操作。例如:
A operator+(A const& ls, A const& rs)
{
A ret = ls;
ret += rs;
return ret;
}