不能调用重载运算符

cannot have an overloaded operator called

本文关键字:运算符 重载 调用 不能      更新时间:2023-10-16

>我尝试从派生类调用一个运算符==

但是如果我使用基类指针,它不起作用,尽管对象是作为派生类创建的

class A 
{
public:
    bool operator==(const A & other)
    {
        cout << "this should never been called" << endl;
        return this==&other;
    }
};
class B : public A
{
public:
    bool operator==(const A & other)
    {
        cout << "this should be called instead" << endl;
        return this==&other;
    }
};
void process(A _b1,A _b2)
{
    if(_b1==_b2)
    {
       cout << "here" << endl;
    }
}
int main() 
{
   B b1;
   B b2;
   process(b1,b2);
}

虽然运算符重载具有相同的签名,但我不明白

请帮帮我

感谢

首先,类 A 中的 bool 运算符==() 应该virtual 。喜欢:

class A 
{
public:
    virtual bool operator==(const A& other) { ... }
};

这意味着,即使你提到A类,它也可以被视为B类,如果这是它的真实情况。

其次,将 B 实例复制到 A 实例。这是您不想要的转换。相反,您应该"通过引用"传递它们。喜欢这个:

void process(A& _b1,A& _b2)
{
    ...
}

这样,当它们被实际处理时,它们仍然引用原始对象,这些对象属于 B 类。

问题是void process(A _b1,A _b2),它会对 A 类中的 B 类进行隐式转换/向上转换,所以它被称为 A 运算符==,你应该改变你的代码以支持多态性:

class A 
{
public:
    virtual bool operator==(const A & other)
    {
        cout << "this should never been called" << endl;
        return this==&other;
    }
};
class B : public A
{
public:
    virtual bool operator==(const A & other)
    {
        cout << "this should be called instead" << endl;
        return this==&other;
    }
};
void process(A& _b1,A& _b2)
{
    if(_b1==_b2)
    {
       cout << "here" << endl;
    }
}
int main() 
{
   B b1;
   B b2;
   process(b1,b2);
}

再见安杰洛