不能有一个重载的运算符调用

时间:2014-04-05 20:47:54

标签: c++ operators

我尝试从派生类

调用operator ==

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

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);
}

虽然运算符重载具有相同的签名,但我没有得到它

请帮助我

THX

2 个答案:

答案 0 :(得分:1)

首先,A类中的bool运算符==()应为virtual。 像:

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

这意味着即使你引用了A类,它也可以被视为B,如果它真的是它。

其次,您将B实例的副本复制到A实例。 那是你不想要的转换。 相反,你应该通过参考&#34;传递它们。 像这样:

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

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

答案 1 :(得分:0)

问题是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);
}

侨 安吉洛