繁体   English   中英

在 c++ 的派生 class 中重载二元运算符>

[英]Overloading binary operator> in a derived class in c++

我已经广泛搜索了这个问题的具体答案,但找不到。 我正在尝试使用虚拟运算符创建一个基本 class>,我可以在派生的 class 中覆盖它。 目前我遇到了问题,因为声明 function 只需要一个输入变量(如“bool operator>(Derived & a)”但试图在 cpp 文件中定义它告诉我它需要两个输入(如“bool operator >(派生和a,派生和b))

我尝试定义内联运算符,但随后我收到错误,它认为派生的 class 仍然是抽象的,因为我将派生类型传递给运算符,如上所示,而不是基本的 class。 但是如果我通过基础 class,那么我无法访问派生成员变量,我需要进行比较。

我想我在这里遗漏了一些简单的东西,但我似乎无法弄清楚它是什么。

希望您能提供帮助。 谢谢

为了从基准的引用/指针进行虚拟调用,您需要在函数中使用base-type,例如

class Derived : public Base
{
    .... 
    bool operator>(Base &a)
    {
         Derived *pa = dynamic_cast<Derived *>(&a);
         return this->something > pa->something;   // Or whatever... 
    }

   .... 
};

如果更改类型,则它将变为不同的函数,并且当您使用基指针或引用来引用operator>时,它将使用基类中的那个。

为什么不将operator>()设为非虚拟,而又不将其称为私有虚拟函数呢?

像这样:

class Base {
public:
    bool operator>(Base &a) {
        return implementingFunction(a);
    }

private:
    virtual bool implementingFunction(Base &a) = 0;
};
#include <iostream>
using namespace std;
class base{
public :
        virtual bool operator> (base& obj) { cout<<"b\n";return true;}
        virtual ~base(){}
};

class derived: public base{
public:
        virtual bool operator> (derived& obj) { cout<<"d\n";return true;}
        ~derived(){}
};

int main()
{

base *a=new derived(),b;
if(*a>b) { delete a; cout<<"Done!\n"; }

return 0;
}

老问题,但我在这里几乎没有看到有用/正确的答案,所以我会添加我的建议:

struct base
{
    virtual ~base() = default;
    virtual bool operator> (base const& obj) const = 0;
};

struct derived: public base
{
    derived(int member) : member(member) {}
    int member = 0;

    virtual bool operator> (base const& obj) const
    {
        return member > static_cast<derived const&>(obj).member;
    }
};

int main()
{    
    //in reality one would use a unique_ptr, of course
    base* a = new derived(1);
    base* b = new derived(0);

    if(*a > *b)
    {
        //do something
    }

     return 0;
}

注意:只有当您确定base const&参数确实是derived const& (例如在 CRTP 中)时,这才安全工作。

如果没有,您应该使用dynamic_cast并添加一些错误处理

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM