Pre 和 post 递增运算符在不同的 类

Pre and post increment operators in different classes

我想创建重载运算符的特征,以避免代码重复。但是当我尝试将 pre 和 post 增量运算符放在不同的 类 中时,编译器会给我一个错误:"operator ++ is ambiguous" 代码:

class A
{
    public: 
    A& operator++(){return *this;}
};

class B
{
    public:
    B operator++(int){return *this;}        
};

class C:public A, public B
{
};

int main()
{
    C c;
    c++;
    ++c;
}

在我的例子中,可以从 A 继承 B,但编译器无法找到 post-increment 运算符。为什么会出现这种情况,正确的做法是什么?

GCC 拒绝该代码,因为它首先执行名称查找而不考虑参数列表,并且名称在两个基 classes 中找到。 Clang 接受代码,但这是由错误引起的。

解决方案是添加 using 并创建一个单独的 class 继承 A 和 B,然后从 class 继承 C。

class A
{
    public: 
    A& operator++(){return *this;}
};

class B
{
    public:
    B operator++(int){return *this;}        
};

class AAndB:public A, public B
{
    public:
    using A::operator++;
    using B::operator++;
};

class C:public AAndB
{
};

int main()
{
    C c;
    c++;
    ++c;
}